UdpClient.ReceiveAsync正确的提前终止 [英] UdpClient.ReceiveAsync correct early termination
问题描述
美好的一天.我使用UdpClient
并对其进行包装.
Good day. I work with UdpClient
and have wrapper upon it.
为了阅读,我有异步方法:
For reading I have asynchronous method:
private async Task<byte[]> Receive(UdpClient client, CancellationToken breakToken)
{
// Выход из async, если произошёл CancellationRequest
breakToken.ThrowIfCancellationRequested();
UdpReceiveResult result;
try
{
result = await client.ReceiveAsync().WithCancellation(breakToken);
}
catch(OperationCanceledException)
{
// Штатная ситуация ручной остановки Task-а
}
return result.Buffer;
}
WithCancellation
是我的提前终止方法:
Where WithCancellation
is my extension-method for early termination:
public static async Task<T> WithCancellation<T>(
this Task<T> task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(
s => ((TaskCompletionSource<bool>)s).TrySetResult(true),
tcs))
if (task != await Task.WhenAny(task, tcs.Task))
throw new OperationCanceledException(cancellationToken);
return await task;
}
并且在手动阅读停止后,当我调用Dispose
时,会出现System.ObjectDisposedException
. CallStack
:
And after manual reading stop, when I call Dispose
, System.ObjectDisposedException
occurs. CallStack
:
> System.dll!System.Net.Sockets.UdpClient.EndReceive(System.IAsyncResult asyncResult, ref System.Net.IPEndPoint remoteEP) Unknown
System.dll!System.Net.Sockets.UdpClient.ReceiveAsync.AnonymousMethod__64_1(System.IAsyncResult ar) Unknown
mscorlib.dll!System.Threading.Tasks.TaskFactory<System.Net.Sockets.UdpReceiveResult>.FromAsyncCoreLogic(System.IAsyncResult iar, System.Func<System.IAsyncResult, System.Net.Sockets.UdpReceiveResult> endFunction, System.Action<System.IAsyncResult> endAction, System.Threading.Tasks.Task<System.Net.Sockets.UdpReceiveResult> promise, bool requiresSynchronization) Unknown
mscorlib.dll!System.Threading.Tasks.TaskFactory<System.Net.Sockets.UdpReceiveResult>.FromAsyncImpl.AnonymousMethod__0(System.IAsyncResult iar) Unknown
System.dll!System.Net.LazyAsyncResult.Complete(System.IntPtr userToken) Unknown
System.dll!System.Net.ContextAwareResult.CompleteCallback(object state) Unknown
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Unknown
System.dll!System.Net.ContextAwareResult.Complete(System.IntPtr userToken) Unknown
System.dll!System.Net.LazyAsyncResult.ProtectedInvokeCallback(object result, System.IntPtr userToken) Unknown
System.dll!System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(uint errorCode, uint numBytes, System.Threading.NativeOverlapped* nativeOverlapped) Unknown
mscorlib.dll!System.Threading._IOCompletionCallback.PerformIOCompletionCallback(uint errorCode, uint numBytes, System.Threading.NativeOverlapped* pOVERLAP) Unknown
如果我正确理解的话,准确地确定ReceiveAsync
中错误的根源.但是我不知道如何解决.
If I understood correctly, root of error in ReceiveAsync
, in my method of stop it to be exact. But i don't know how to fix it.
我该怎么做才能纠正此错误?
What i must do to correct this error?
在usr注释后更新:
Update after usr comment:
private async Task<byte[]> Receive(UdpClient client, CancellationToken breakToken)
{
// Выход из async, если произошёл CancellationRequest
breakToken.ThrowIfCancellationRequested();
UdpReceiveResult result;
try
{
result = await client.ReceiveAsync().WithCancellation(breakToken);
}
catch(OperationCanceledException)
{
// Штатная ситуация ручной остановки Task-а
}
catch(ObjectDisposedException) { }
return result.Buffer;
}
和Dispose
调用:
public void Dispose()
{
this.cancelRecieve?.Cancel();
this.cancelRecieve?.Dispose();
try
{
this.client?.Close();
}
catch(ObjectDisposedException) { }
}
但是catch
不会对ObjectDisposedException
做出反应.
推荐答案
因此,在经历了近一个星期的痛苦之后,我找到了原因和解决方案.
And so, after nearly a week of suffering, I have found the reason and solution.
起初,我查看了UdpClient
源代码. ReceiveAsync
方法:
At first, I looked at the UdpClient
source code. The ReceiveAsync
method:
[HostProtection(ExternalThreading = true)]
public Task<UdpReceiveResult> ReceiveAsync()
{
return Task<UdpReceiveResult>.Factory.FromAsync((callback, state) => BeginReceive(callback, state), (ar)=>
{
IPEndPoint remoteEP = null;
Byte[] buffer = EndReceive(ar, ref remoteEP);
return new UdpReceiveResult(buffer, remoteEP);
}, null);
}
第二,我发现这篇帖子的答案很完美:如何终止套接字的BeginReceive()吗?,其中说:
At second, I found this post with perfect answer:How to abort socket's BeginReceive()?, in which said:
要取消对BeginConnect()方法的挂起调用,请关闭Socket.在异步操作进行过程中调用Close()方法时,将调用提供给BeginConnect()方法的回调.随后对EndConnect(IAsyncResult)方法的调用将引发ObjectDisposedException,以指示该操作已被取消.
To cancel a pending call to the BeginConnect() method, close the Socket. When the Close() method is called while an asynchronous operation is in progress, the callback provided to the BeginConnect() method is called. A subsequent call to the EndConnect(IAsyncResult) method will throw an ObjectDisposedException to indicate that the operation has been cancelled.
而且,正如我们所看到的,原始的ReceiveAsync
方法返回了ObjectDisposedException
,因为IOOperation
在调用Close
之后尚未完成.
And, as we can see, the original ReceiveAsync
method return us the ObjectDisposedException
, because IOOperation
has not been completed after Close
invoking.
为克服此问题,我已经这样做:
新的ReceiveAsync
实现:
/// <summary>
/// Асинхронный запрос на ожидание приёма данных с возможностью досрочного выхода
/// (для выхода из ожидания вызовите метод Disconnect())
/// </summary>
/// <param name="client">Рабочий экземпляр класса UdpClient</param>
/// <param name="breakToken">Признак досрочного завершения</param>
/// <returns>Если breakToken произошёл до вызова данного метода или в режиме ожидания
/// ответа, вернёт пустой UdpReceiveResult; при удачном получении ответа-результат
/// асинхронной операции чтения</returns>
public Task<UdpReceiveResult> ReceiveAsync(UdpClient client, CancellationToken breakToken)
=> breakToken.IsCancellationRequested
? Task<UdpReceiveResult>.Run(() => new UdpReceiveResult())
: Task<UdpReceiveResult>.Factory.FromAsync(
(callback, state) => client.BeginReceive(callback, state),
(ar) =>
{
/// Предотвращение <exception cref="ObjectDisposedException"/>
if (breakToken.IsCancellationRequested)
return new UdpReceiveResult();
IPEndPoint remoteEP = null;
var buffer = client.EndReceive(ar, ref remoteEP);
return new UdpReceiveResult(buffer, remoteEP);
},
null);
新的Dispose
实现:
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.cancelReceive?.Cancel();
this.client?.Close();
this.cancelReceive?.Dispose();
}
}
我非常希望我的决定能够使别人摆脱我所经历的痛苦.
I very much hope, that my decision will deprive someone else of the pain that I experienced.
这篇关于UdpClient.ReceiveAsync正确的提前终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!