Parallel Processing Routine C#

Asked

Viewed 192 times

4

I would like to start a data processing method whenever I receive a String with START content through the Transceiver event.Receivelineeventhandler(); but this method will have a processing time as there will be timeout among other resources. The problem is that while doing this processing, I cannot stop the program, as the event may receive another string that must be processed by other implemented methods, in addition there will always be a receiver address contained in the string, and there are cases where it will be necessary to process the string received by the same Sendandwaitforresponse() method and use the received address to target the data, but this may already be being used by a received START from another address, Can anyone help me with such a problem ? Some light ?

I was able to use the Sendandwaitforresponse() method in a separate thread, so I can’t stop the whole program. But there will be cases where I need to execute the Method to treat other information coming from another address simultaneously

    Transceiver.ReceiveLine += new Transceiver.ReceiveLineEventHandler(ProcessReceived);
    public string address = "";

    void ProcessReceived(string line)
    {   

        string[] dados = line.Split('|');
        address = dados[1];
        if (dados[0] == "RECOVERY"){...}
        if (dados[0] == "COMMANDMODE"){...}
        else if (dados[0] == "START"){
        SendAndWaitForResponse(address,line);
    }

    public void SendAndWaitForResponse(string endereco, string line)
    {
     SendMessage(endereco,line);
         ...
    }
  • what version of the Framework you are using? may use async/await?

  • .Net Framwework 4.5, yes, you can use Async

  • I never tried to do an asynchronous Eventhandler, but try the following.: async void ProcessReceived(string line) and await Task.Run(() => { SendAndWaitForResponse(address,line) });

  • It worked correctly Toby, also had never thought to create an asynchronous Eventhandler =P

  • I added an answer with the suggestion.

1 answer

1


You can make an asynchronous call on Eventhandler.:

Transceiver.ReceiveLine += new Transceiver.ReceiveLineEventHandler(ProcessReceived);
public string address = "";

async void ProcessReceived(string line)
{   
    string[] dados = line.Split('|');
    address = dados[1];
    if (dados[0] == "RECOVERY"){...}
    if (dados[0] == "COMMANDMODE"){...}
    else if (dados[0] == "START"){
    await Task.Run(() => {
        SendAndWaitForResponse(address,line);
    });
}

public void SendAndWaitForResponse(string endereco, string line)
{
    SendMessage(endereco,line);
    ...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.