对c#和任务来说很新...试图找到将UDP客户端包装成FromAsync(...)的正确语法,似乎我错过了一些参数...(不能使用ReceiveAsync,因为它应该可以使用 .NET 4.0)
public Task<byte[]> GetUDPmessageAsync()
{
byte[] data = new byte[100];
myUdpClient = new UdpClient(12000);
Task<byte[]> task = Task<byte[]>.Factory.FromAsync(myUdpClient.BeginReceive, myUdpClient.EndReceive,?,?);
}
答案 0 :(得分:3)
我认为您不能使用FromAsync
,因为UdpClient.EndReceive
会使用ref参数,这会使其与FromAsync
的所有重载不兼容。您可以创建自己的扩展方法:
public static Task<byte[]> ReceiveAsync(this UdpClient client, IPEndPoint endpoint)
{
TaskCompletionSource<byte[]> tcs = new TaskCompletionSource<byte[]>();
AsyncCallback callback = ar => {
try
{
byte[] bytes = client.EndReceive(ar, ref endpoint);
tcs.SetResult(bytes);
}
catch(Exception ex)
{
tcs.SetException(ex);
}
};
client.BeginReceive(callback, null);
return tcs.Task;
}