调用后台工作人员 [英] Invoke inside backgroundworker

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

问题描述

我正在使用Invoke()通过后台工作人员执行耗时的功能时显示另一种形式来获取一些用户输入.


I am using Invoke() to get some user input by showing another form while executing a time consuming function by a background worker.


//funcation called inside DoWork of a backgroundworker
public bool ShowSupportLogon()
{
    bool erResult = false;
    System.Threading.Thread.Sleep(5000);//Time-consuming tasks
    //passing control to foreground/main thread to show the form
    this.Invoke((MethodInvoker)delegate()
    {
        DialogResult dr = er.ShowDialog();//er is the object of another form(global variable)
        if (dr == DialogResult.OK)
        {
            erResult = true;
        }
        else
        {
            erResult = false;
        }
    });
    System.Threading.Thread.Sleep(2000);//Time-consuming tasks
    return erResult;
}



我了解到``this.Invoke((MethodInvoker)delegate()''内的代码块是在主线程中执行的,但我的问题是,后台工作程序是否有可能在此代码块完成之前继续执行.



I understand that the block inside ''this.Invoke((MethodInvoker)delegate()'' is executed in the main thread but my question, is there any chance that background worker continue execution before the completion of this block.
Is there anything else that I should be worried about?

推荐答案

托尼!

我的建议是将任务分为两部分.好的,如果第二部分依赖于第一部分,则必须跟踪状态,但是如果您创建具有两个方法的类(对于任务的每个部分一个),并使用其中的字段进行跟踪,这将不是问题.课.
从您的GUI中,您将调用任务的一部分(BackgroundWorker或Thread)
然后完成表单输入工作,将值保存在您创建的类中,并在另一个线程中调用第二部分的方法.

那就是我更喜欢这样做的方式,您怎么看?


干杯

曼弗雷德(Manfred)
Hi Tony!

My advice is that the task be split into two parts. Ok you will have to track the state if the second part relies on the first one, but that will not be a problem if you create a class with two methods, one for each part of the task, and do the tracking with fields in this class.
From your GUI you call part one of the task (BackgroundWorker or Thread)
and when that is done do your form input stuff , saving the value in the class you created and invoke the method for the second part in another thread.

That''s the way I''d prefer doing it, what do you think?


Cheers

Manfred


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

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