lundi 15 février 2021

C# multithreads on State Desing Pattern

My program runs several threads. Each thread creates its own StateContext. The model is something like this ^^. Every state keeps some data with an unique ID. When the program started, some datas looks like these:

Thread 1: it's data ID that assigned while context creating is 1. Also the data in carrying through different states have ID 1. Thread 2: it's data ID that assigned while context creating is 2. Also the data in carrying through different states have ID 2.

But somehow, while program is running, different threads and different objects are merging. Every thread is creating its own States and Datas but this is happening:

Thread 1: it's data ID that assigned while context creating is 1. Also the data in carrying through different states have ID 2. Thread 2: it's data ID that assigned while context creating is 2. Also the data in carrying through different states have ID 1.

I think I didn't understand the multithreading or state design pattern. I don't understand what is wrong, what am I missing?

Code:

static void Main()
{
    foreach (MachineOperation operation in Operations)
    {
        var machine = operation.MachineInfo.Machine;

        if (!operation.IsRunning() && machine.Enabled)
        {
            operation.OperationThread = new Thread(new ThreadStart(operation.OnWorking));
            operation.OperationThread.Start();
        }
    }
}


public void OnWorking()
{
    StateContext context = new StateContext(new DataCollectState(), MachineInfo);

    while (isRunning)
    {
        Sleep(8 * 1000);
        
        context.Request();
    }
}

public class StateContext
{
    public IState State { get; set; }

    public StateContext(IState state)
    {
        State = state;
    }

    public void Request()
    {  
        State.Change(this);
    }
}


public class DataCollectState : IState
{
    private IDataOperation DataOperation { get; set; }
    public Info Info { get; set; }

    public DataCollectState(Info MachineInfo)
    {
        try
        {
            this.Info = MachineInfo;

            if (Info.DataClass.GetType() == typeof(PLCType))
                DataOperation = new DataOperations.PLC_Machine.PLCOperation();
            else if (Info.DataClass.GetType() == typeof(SAPSQLType))
                DataOperation = new DataOperations.SAP_SQL.SQLOperation();

            DataOperation.SetMachineInfo(Info);
            DataOperation.GetDatas();
            DataOperation.CheckDatasAndSaveToTables();
            this.Info = DataOperation.UpdateMachineInfo();
        }
        catch(Exception e) { }
    }

    public void Change(StateContext context)
    {
        context.State = new UnplannedStopState(Info);
    }
}

Aucun commentaire:

Enregistrer un commentaire