这是 C# 5 (IIRC) 之前的一般异步模式。
public static string SendData (...) {
}
public static IAsyncResult BeginSendData(..., AsyncCallback cb) {
var f = new Func<..., string>(SendData);
return f.BeginInvoke(..., cb, f);
}
public static string EndSendData(IAsyncResult ar) {
return ((Func<..., string>) ar.AsyncState).EndInvoke(ar);
}
用法:
BeginSendData(..., ar =>
{
var result = EndSendData(ar);
// do something with result
});
完整的控制台示例:
public static string SendData(int i)
{
// sample payload
Thread.Sleep(i);
return i.ToString();
}
public static IAsyncResult BeginSendData(int i, AsyncCallback cb)
{
var f = new Func<int, string>(SendData);
return f.BeginInvoke(i, cb, f);
}
public static string EndSendData(IAsyncResult ar)
{
return ((Func<int, string>)ar.AsyncState).EndInvoke(ar);
}
static void Main(string[] args)
{
BeginSendData(2000, ar =>
{
var result = EndSendData(ar);
Console.WriteLine("Done: {0}", result);
});
Console.WriteLine("Waiting");
Console.ReadLine();
}
以上将打印:
Waiting
Done: 2000