gpt4 book ai didi

c# - Socket.EndAccept 上的 System.AggregateException 与 TaskFactory.FromAsync

转载 作者:行者123 更新时间:2023-11-30 17:53:06 24 4
gpt4 key购买 nike

我正在使用套接字 (.Net 4 - VS 2010 SP1) 进行异步操作,一切似乎都正常。然而,在编写并运行自动化测试后,它通过了绿色但显示异常消息:

---- UNHANDLED EXCEPTION ----
Thread Name: <No Name>
System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.
at System.Net.Sockets.Socket.EndAccept(IAsyncResult asyncResult)
at P2PNet.Listener.<ListenForConnections>b__0(IAsyncResult r) in C:\Users\lucas.ontivero\Documents\Visual Studio 2010\Projects\P2PNet\P2PNet\Listener.cs:line 76
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endMethod, TaskCompletionSource`1 tcs)
--- End of inner exception stack trace ---
at System.Threading.Tasks.TaskExceptionHolder.Finalize()
---> (Inner Exception #0) System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.
at System.Net.Sockets.Socket.EndAccept(IAsyncResult asyncResult)
at P2PNet.Listener.<ListenForConnections>b__0(IAsyncResult r) in C:\Users\lucas.ontivero\Documents\Visual Studio 2010\Projects\P2PNet\P2PNet\Listener.cs:line 76
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endMethod, TaskCompletionSource`1 tcs)<---

我知道那个异常是什么意思,它意味着在调用 EndAccept 方法之前套接字已关闭。我对此没有问题,我真正不知道的是如何以优雅的方式防止该异常。这是我的代码:

    private void ListenForConnections()
{
try
{
Task.Factory.FromAsync<Socket>(_listener.BeginAccept, _listener.EndAccept, _listener)
.ContinueWith(task =>
{
if (task.IsFaulted) return;
ListenForConnections();

var newSocket = task.Result;
RaiseClientConnectedEvent(new ConnectionEventArgs(newSocket));
}, TaskContinuationOptions.OnlyOnRanToCompletion);
}
catch (ObjectDisposedException)
{
}

我试过这条线:

if (task.IsFaulted) return; 

还有:

.ContinueWith(task=>{}, TaskContinuation.OnlyOnFault);

但是无论如何都会抛出异常。防止异常的方法是什么?

谢谢!

最佳答案

你的线路:

if (task.IsFaulted) return; 

返回未出错,因为您正在检查延续任务的状态,而不是前面的任务。将其更改为:

    private void ListenForConnections() {
Task<Socket> listentask = Task.Factory.FromAsync<Socket>(_listener.BeginAccept, _listener.EndAccept, _listener);
listentask.ContinueWith(task => {
if (listentask.IsFaulted) {
//observe exception
Exception exception = listentask.Exception;
return;
}
ListenForConnections();

var newSocket = listentask.Result;
RaiseClientConnectedEvent(new ConnectionEventArgs(newSocket));
});
//don't forget to start it
listentask.Start();
}

关于c# - Socket.EndAccept 上的 System.AggregateException 与 TaskFactory.FromAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17775839/

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