Using async method for message loop in C #

I am making an online communication application and I would like to process messages asynchronously. I found the asynchronous wait pattern useful when implementing a message loop.

Below I guess:

CancellationTokenSource cts=new CancellationTokenSource(); //This is used to disconnect the client.

public Action<Member> OnNewMember; //Callback field

async void NewMemberCallback(ConnectionController c, Member m, Stream stream){
    //This is called when a connection with a new member is established.
    //The class ConnectionController is used to absorb the difference in protocol between TCP and UDP.

    MessageLoop(c, m,stream,cts.Token);
    if(OnNewMember!=null)OnNewMember(m);
}

async Task MessageLoop(ConnectionController c, Member m, Stream stream, CancellationToken ct){
    MemoryStream msgbuffer=new MemoryStream();
    MemoryStream buffer2=new MemoryStream();

    while(true){
        try{
            await ReceiveandSplitMessage(stream, msgbuffer,buffer2,ct); //This stops until data is received.
            DecodeandProcessMessage(msgbuffer);
        catch( ...Exception ex){
            //When the client disconnects
            c.ClientDisconnected(m);
            return;
        }

    }
}

Then I got some warning that MessageLoop is not expected in NewMemberCallback. I really don't have to wait for the MessageLoop method, because the method does not return until the connection is disconnected. Is it good practice to use async like this? I heard that not expecting an asynchronous method is not good, but I also heard that I have to eliminate unnecessary expectations. Or is it even considered incorrect to use an asynchronous template for a message loop?

+4
2

, , . :

Task _messageLoopTask = null;

async void NewMemberCallback(ConnectionController c, Member m, Stream stream)
{
    if (_messageLoopTask != null)
    {
        // handle re-entrancy
        MessageBox.Show("Already started!");
        return;
    }

    _messageLoopTask = MessageLoop(c, m,stream,cts.Token);

    if (OnNewMember!=null) OnNewMember(m);

    try
    {
        await _messageLoopTask;
    }
    catch (OperationCanceledException ex)
    {
        // swallow cancelation
    }
    catch (AggregateException ex) 
    { 
        // swallow cancelation
        ex.Handle(ex => ex is OperationCanceledException);
    }
    finally
    {
        _messageLoopTask = null;
    }
}

Lucian Wischik " " .

MessageLoop, , .

+4

await MessageLoop(c, m,stream,cts.Token);, , await, . . , , c.ClientDisconnected(m); throw , , , Task, , , @Noseratio

, , .

, ? - , , , .

+3

Source: https://habr.com/ru/post/1542165/


All Articles