在C#中设计多线程的最佳方法

时间:2018-07-21 09:44:37

标签: c# multithreading design-patterns thread-safety

我很难考虑使用OOP进行多线程设计。 我们有一个简化的场景。我们有3个班级。

    class Add
    {
    private int _x;
    private int _y;
    private int _sum;
    private Thread _Thread;

    public Thread Thread
    {
        get
        {
            return this._Thread;
        }
        set
        {
            this._Thread = value;
        }
    }

    public Add(int x, int y)
    {
        this._x = x;
        this._y = y;
    }

    public void Addnumber()
    {
        Random rm = new Random();
        for (int i = 1; i < 1000; i++)
        {
            this._x = rm.Next()%100;
            this._y = rm.Next()%100;
            this._sum = _x + _y;

        }
    }



    public string PrintAdd()
    {
        return this._Thread.Name + " - " + this._sum.ToString();
    }

另一个类似的执行减法的类。

和Log类具有2种方法。一种用于在控制台中写入,另一种用于在文件中写入。

目标是我们有4个线程: 一个加法,一个减法,一个对数和一个主线程。

(下一步是通过一个操作(加或减)和一个日志,另一个操作和另一个日志来同步.....

现在最好的可读性设计在哪里是多线程OOP? 在任何类中有一个线程作为字段并与主类一起调用?是对的吗?

        Add a = new Add(10, 9);
        Sub b = new Sub(10, 9);

        a.Thread = new Thread(a.Addnumber);
        a.Thread.Name = "ThreadAdd";
        a.Thread.Start();

其他解决方案? 耐心点!

对不起,它们是使用线程的第一种方法。对我来说并不简单。

0 个答案:

没有答案