BackgroundWorker.RunWorkerCompleted和线程 [英] BackgroundWorker.RunWorkerCompleted and threading

查看:327
本文介绍了BackgroundWorker.RunWorkerCompleted和线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AFAIK,这个事件被承诺在创建者线程被称为(<一href="http://stackoverflow.com/questions/2806814/c-sharp-backgroundworker-runworkercompleted-event">BackgroundWorker RunWorkerCompleted事件);而在大多数情况下,它的承诺。然而,有时RunWorkerCompleted称为的没有的在创建BackgroundWorker的对象的线程。

AFAIK, this event is promised to be called in the creator thread (BackgroundWorker RunWorkerCompleted Event); and in the most cases, it does as promised. However, sometimes RunWorkerCompleted is called not in the thread that created BackgroundWorker object.

更新:code是这样的:

Update: Code is like this:

Trace.WriteLine(Thread.CurrentThread.ManagedThreadId);
var worker = new BackgroundWorker();
worker.DoWork += (s, args) => Trace.WriteLine(Thread.CurrentThread.ManagedThreadId);
worker.RunWorkerCompleted += (s, args) => Trace.WriteLine(Thread.CurrentThread.ManagedThreadId);
worker.RunWorkerAsync();

输出为1 7 7(正确的输出必须是1 7 1)
任何想法?

Output is 1 7 7 (correct output must be 1 7 1)
Any ideas?

推荐答案

BackgroundWorker的是专为GUI应用程序。

BackgroundWorker is designed for GUI applications.

我猜你这样做在一个控制台应用程序或一些其他类型的应用程序以外的WinForms或WPF的。

I'm guessing you're doing this in a console application or some other type of application other than Winforms or WPF.

BackgroundWorker的使用由 SynchronizationContext.Current提供的同步模型来分派事件。在GUI应用程序,SynchronizationContext.Current是与 WindowsFormsSynchronizationContext ,它通过调用UI线程上提供同步初始化。

BackgroundWorker uses the synchronization model provided by SynchronizationContext.Current to dispatch events. In a GUI application, SynchronizationContext.Current is initialized with a WindowsFormsSynchronizationContext, which provides synchronization by Invoking on the UI thread.

但在非GUI应用程序,SyncronizationContext.Current只是一个的SynchronizationContext 对象,该对象的(从MSDN)

But in a non-GUI application, SyncronizationContext.Current is just a SynchronizationContext object, which (from MSDN):

是提供一个自由线程上下文不同步的基类。

is a base class that provides a free-threaded context with no synchronization.

在换句话说,它通过简单的线程池调度,所以你通常会得到不同的线程每次。

In other words it simply dispatches via the threadpool, so you'll usually get a different thread each time.

如果你在一个WinForms应用程序运行code,它会正常工作。

If you run your code in a winforms application, it will work as expected.

这篇关于BackgroundWorker.RunWorkerCompleted和线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆