0

An application is using an OPC-Client. This OPC-Client fires for each value change an event. In the Event handler I am using the Task.Factory.StartNew to call a method. But now, i recognized that the method is called in a false order. I want to call the method in the right sequence. And it is mandatory to call this method asynchronously, because each method call takedifferent execution time.

Event Handler Snippet:

        private void OpcClientInterface_ValueChangeEvent(object sender, OPCClient.OPCClient.strMonitoredItems e)
    {

        string sValue = String.Empty;
        for (int i = 0; i < listOPCItemID.Count; i++)
        {
            if (listOPCItemID[i].Equals(e.sNodeID))
            {
                Task.Factory.StartNew(() => GetResult(e.oValue, e.sNodeID));
                break;
            }
        }
    }
Gerry Seel
  • 63
  • 7
  • 2
    You are using tasks. Tasks are started and executed **asynchronously**. There is no pre-determined order in which tasks will run. Nor will they be executed sequentially one after the other. That's why it is called **asynchronous**. Why would you even need to use (asynchronous) tasks here? –  Jun 24 '19 at 09:10
  • Tell us a bit more, what do you mean by false order. – Tony Hopkinson Jun 24 '19 at 09:10
  • The worst case is, that this event could be fired every millisecond. I want to improve the performance with an asynchronously call of the method. – Gerry Seel Jun 24 '19 at 09:40
  • False order means, that sometimes for example the third value change will be executed and finished before the first – Gerry Seel Jun 24 '19 at 09:41
  • 1
    A millisecond is a relatively long time period for a modern computer. What is the actual problem at hand here? Is the GetResult method computationally too costly or relying on slow-ish external resources, or is there another reason i can't think of right now? –  Jun 24 '19 at 09:42
  • 1
    Anyways, you could always employ some FIFO queue to buffer the incoming events inside your event handler. Then some background thread in a loop would take the oValue/sNodeID values from the FIFO queue (nicely in order) and execute GetResult. Thus, you will have decoupled the execution-time performance behavior of taking the incoming events from the execution-time performance behavior of proccessing the event information, while maintaining sequential processing of the events. –  Jun 24 '19 at 09:52
  • Question: Now I am just calling the Method like that "GetResult(e.oValue, e.sNodeID);" instead of using a asynchrounous task. The sequence is now in the right order. Is it a typical way to call a method inside an event like I do now? Or is there a better way for doing that? – Gerry Seel Jun 24 '19 at 10:19
  • 1
    You could look at this question for ideas: https://stackoverflow.com/questions/25691679/best-way-in-net-to-manage-queue-of-tasks-on-a-separate-single-thread – iSpain17 Jun 24 '19 at 10:36

0 Answers0