gpt4 book ai didi

c# - 在 C# 中使用异步方法进行消息循环

转载 作者:太空狗 更新时间:2023-10-30 00:40:55 26 4
gpt4 key购买 nike

我正在制作一个在线通信应用程序,我想异步处理消息。我发现异步等待模式在实现消息循环方面很有用。

下面是我目前得到的:

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;
}

}
}

然后我收到一些警告,说在 NewMemberCallback 中,没有等待对 MessageLoop 的调用。我实际上不需要等待 MessageLoop 方法,因为该方法在连接断开之前不会返回。像这样使用异步被认为是一种好习惯吗?我听说不等待异步方法不好,但我也听说我应该消除不必要的等待。还是将异步模式用于消息循环甚至被认为是不好的?

最佳答案

通常您希望跟踪已开始的任务,以避免重入并处理异常。示例:

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 的 "Async re-entrancy, and the patterns to deal with it" .

如果您可以有多个 MessageLoop 实例,那么您就不必担心重入问题,但您仍然希望观察异常。

关于c# - 在 C# 中使用异步方法进行消息循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23887489/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com