samedi 21 juillet 2018

Best way to design multithread in c#

I have difficult to think about multithread design with OOP. we have this semplified scenario. We have 3 class.

    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();
    }

another similar class that performs the subtraction..

and the Log class that have 2 method.. one for write in console and one to write in file.

The goal is we have 4 thread: one to add , one to subtract , one to log and one main Thread.

(next step is synchronized by one operation(add or sub) and one log, other one operation and other one log.....

Now where is the best readable design a multithread OOP? One thread in any class as field and call with main class? is right?

        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();

Other solution with delegats?? Be patient!

Sorry, they are the first approaches with the threads.. Not simple for me.

Aucun commentaire:

Enregistrer un commentaire