Wait for another method to be called and then continue with the result

I am trying to call a method from another. Dll file. It sends a message through the VPN, and then returns the received message from another computer.

As you now need time to send and receive a message, VpnObjectjust send a message, and I have to wait for the listener to call RecievedMessage.

This method is similar to this one!

    public string RecievedMessage()
    {
        string Recieved ;
        // Some VPN Code  and then return the result;
        return Recieved;
    }

    public string SendAndRecieveMessage(string MessageToSend)
    {
        string RecievedAnswer = string.Empty;

        // Now Sending Message through the VPN
        VpnObject.SendMessage(MessageToSend);

        //Then want to Recieve the answer and return the answer here .

        return RecievedAnswer;
    }

I just think how to wait RecievedMessagefor the call and then return the result.

You know that just using a variable and assigning it a value and checking for while, but it drastically reduced performance.

Do I need to continue working with SendAndRecieveMessageonly after a call RecievedMessage? (I think this is something asynchronous and waiting, but I don’t know how!)

: VpnObject - vpn. , (RecievedMessage) .

+4
2

, , , , .

Task. :

public Task<string> SendAndRecieveMessage(string MessageToSend)

, , , API VpnObject. TaskCompletionSource .

VpnObject , :

public Task<string> SendAndReceiveMessage(string messageToSend)
{
    var tcs = new TaskCompletionSource<string>();
    ...
    VpnObject.OnMessageReceived += (s, e) => tcs.SetResult(e.Message);
    ...
    return tcs.Task;
}

VpnObject , :

public Task<string> SendAndReceiveMessage(string messageToSend)
{
    var tcs = new TaskCompletionSource<string>();
    ...
    VpnObject.OnMessageReceived(message => tcs.SetResult(message));
    ...
    return tcs.Task;
}

VpnObject , :

public async Task<string> SendAndReceiveMessage(string messageToSend)
{
    var tcs = new TaskCompletionSource<string>();
    ...
    while(!VpnObject.IsMessageReceived)
        await Task.Delay(500); // Adjust to a reasonable polling interval
    ...
    return VpnObject.Message;
}
+2

, , .

. , , # .

, VPN, - , , async #.

VPN- . , , , async, await . VPN.

- .

public Task<string> ReceivedMessage()
{
    //get the response from the VPN Object.
    string Received = VpnObject.GetResponse(); 
    var ts = new TaskCompletionSource<string>();
    ts.SetResult(Received);

    // Some VPN Code  and then return the result;
    return ts.Task;
}

public async Task<string> SendAndReceiveMessageAsync(string MessageToSend)
{
    string result = string.Empty;

    // Now Sending Message through the VPN
    VpnObject.SendMessage(MessageToSend);

    result = await ReceivedMessage();

    return result;
}
0

All Articles