【发布时间】:2009-11-23 17:59:16
【问题描述】:
我对执行以下操作有一些疑问:
public class Test
{
delegate int TestDelegate(string parameter);
static void Main()
{
TestDelegate d = new TestDelegate(PrintOut);
d.BeginInvoke("Hello", new AsyncCallback(Callback), d);
// Give the callback time to execute - otherwise the app
// may terminate before it is called
Thread.Sleep(1000);
Console.ReadKey(true);
}
static int PrintOut(string parameter)
{
Console.WriteLine(parameter);
return 5;
}
static void Callback(IAsyncResult ar)
{
TestDelegate d = (TestDelegate)ar.AsyncState;
Console.WriteLine("Delegate returned {0}", d.EndInvoke(ar));
}
}
1) TestDelegate 已经指向一个方法 ("PrintOut")。为什么还要在 d.BeginInvoke( "Hello",new AysncCallback(Callback),d);。这是否意味着 d.BeginInvoke 并行执行“PrintOut”和“Callback”?你能逐行解释到底发生了什么吗?
2) 通常,异步执行意味着“线程”的执行是不可预测的 还是最快的执行?
3) TestDelegate d = (TestDelegate)ar.AsyncState;
“TestDelegate” d 是一个委托。如何将其转换为归档或财产? (ar.AsyncState)
4) 能否提供一些现场示例,我需要在哪里使用此异步执行?
【问题讨论】:
标签: c# asynchronous methods