相关疑难解决方法(0)

Invoke()和BeginInvoke()之间有什么区别

只是想知道BeginInvoke()和之间的区别Invoke()是什么?

主要是每个人将用于什么.

编辑:创建一个线程对象和调用invoke并只调用BeginInvoke()一个委托有什么区别?或者他们是一样的吗?

.net c# multithreading invoke begininvoke

383
推荐指数
6
解决办法
18万
查看次数

c#Delegate.BeginInvoke()和线程ID

假设我们有一些像这样的简单代码:

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)

c# multithreading delegates

1
推荐指数
1
解决办法
6822
查看次数

标签 统计

c# ×2

multithreading ×2

.net ×1

begininvoke ×1

delegates ×1

invoke ×1