在BackgroundWorker的调用的ShowDialog [英] Calling ShowDialog in BackgroundWorker

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

问题描述

我在我的背景工人做一个同步任务WinForms应用程序,添加新文件,删除旧的特性等。



在我的后台工作的代码,我想显示自定义表单用户告诉他什么都会被删除,如果他继续,用YES / NO按钮来得到他的反馈是什么将被添加。



我想知道如果它是确定做后台工作的方法的doWork这样的事情?
如果没有,我应该怎么办呢?



请指教..

 私人无效backgroundWorker1_DoWork(对象发件人,DoWorkEventArgs E)
{
MyForm的F =新建MyForm();
f.FilesToAddDelete(..);
DialogResult的结果= f.ShowDialog();
如果(无...)
的回报;
,否则
//继续工作......
}


解决方案

如果你试试这个,你会看到自己,这是行不通的,因为的BackgroundWorker 线程没有的STA (它来自的管理线程池)。



事情的本质是,你不能从一个工人thread¹显示的用户界面,让你必须解决它。你应该传递给您的应用程序的UI元素的引用(主要形式将是一个不错的选择),然后使用的 调用 编组为用户交互的UI线程的请求。准系统例如:

 类的MainForm 
{

//所有其​​他在这里$成员b
$ b酒店的公共布尔AskForConfirmation()
{
变种confirmationForm =新confirmationForm();
返回confirmationForm.ShowDialog()== DialogResult.Yes;
}
}

和后台工作人员会做这样的:

  //我认为MainForm中已经以某种方式传递给BackgroundWorker的
VAR的结果=(布尔)mainForm.Invoke(mainForm.AskForConfirmation );
如果(结果){...}






¹技术上讲,你不能从一个线程不是STA显示用户界面。如果您创建一个工作线程自己,你可以选择让它STA反正,但如果它来自线程池不存在这样的可能性。


I have a WinForms application in which my background worker is doing a sync task, adding new files, removing old ones etc.

In my background worker code I want to show a custom form to user telling him what will be deleted and what will be added if he continues, with YES/NO buttons to get his feedback.

I was wondering if it is ok to do something like this in background worker's doWork method? If not, how should I do it?

Please advise..

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
   MyForm f = new MyForm();
   f.FilesToAddDelete(..);
   DialogResult result = f.ShowDialog();
   if(No...)
   return;
   else
   //keep working...
}

解决方案

If you try this you will see for yourself that it will not work because the BackgroundWorker thread is not STA (it comes from the managed thread pool).

The essence of the matter is that you cannot show user interface from a worker thread¹, so you must work around it. You should pass a reference to a UI element of your application (the main form would be a good choice) and then use Invoke to marshal a request for user interaction to your UI thread. A barebones example:

class MainForm
{

    // all other members here

    public bool AskForConfirmation()
    {
        var confirmationForm = new ConfirmationForm();
        return confirmationForm.ShowDialog() == DialogResult.Yes;
    }
}

And the background worker would do this:

// I assume that mainForm has been passed somehow to BackgroundWorker
var result = (bool)mainForm.Invoke(mainForm.AskForConfirmation);
if (result) { ... }


¹ Technically, you cannot show user interface from a thread that is not STA. If you create a worker thread yourself you can choose to make it STA anyway, but if it comes from the thread pool there is no such possibility.

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

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