基于 “Async/Await” 关键字实现 Socket AcceptYield() 函数。
用法:Socket server;while (!this.IsDisposed && (server = this._server) != null){Socket socket = await AcceptYield(server);if (socket == null){
·
用法:
Socket server;
while (!this.IsDisposed && (server = this._server) != null)
{
Socket socket = await AcceptYield(server);
if (socket == null)
{
continue;
}
// TODO: Your are code here.
}
实现:
#if NETCOREAPP
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static Task<Socket> AcceptYield(Socket socket)
{
TaskCompletionSource<Socket> tcs = new TaskCompletionSource<Socket>();
IAsyncResult r = null;
if (socket != null)
{
try
{
r = socket.BeginAccept(ar =>
{
try
{
tcs.SetResult(socket.EndAccept(ar));
}
catch
{
tcs.SetResult(null);
}
}, null);
}
catch { }
}
else { }
if (r == null)
{
tcs.SetResult(null);
}
return tcs.Task;
}
更多推荐
已为社区贡献4条内容
所有评论(0)