只是想知道BeginInvoke()和之间的区别Invoke()是什么?
主要是每个人将用于什么.
编辑:创建一个线程对象和调用invoke并只调用BeginInvoke()一个委托有什么区别?或者他们是一样的吗?
假设我们有一些像这样的简单代码:
private static void Main()
{
Console.WriteLine("Main thread {0}\n", Thread.CurrentThread.ManagedThreadId);
Action asyncCaller1 = () => LongPerfomingTask(5);
Action asyncCaller2 = () => LongPerfomingTask(3);
var asyncResult1 = asyncCaller1.BeginInvoke(null, null);
var asyncResult2 = asyncCaller2.BeginInvoke(null, null);
asyncResult1.AsyncWaitHandle.WaitOne();
asyncResult2.AsyncWaitHandle.WaitOne();
Console.WriteLine("Done");
}
private static void LongPerfomringTask(int seconds)
{
Thread.Sleep(TimeSpan.FromSeconds(seconds));
Console.WriteLine("Thread {0} finished execution", Thread.CurrentThread.ManagedThreadId);
}
Run Code Online (Sandbox Code Playgroud)
Delegate.BeginInvoke()不会创建一个线程,它在调用者的线程中处于空闲状态时执行代码,对吧?那么,为什么这个示例应用程序的输出是这样的:
Main thread 1
Thread 4 finished execution
Thread 3 finished execution
Done
Run Code Online (Sandbox Code Playgroud)