使用匿名方法定义backgroundworker的RunWorkerCompleted? [英] Define backgroundworker's RunWorkerCompleted with an anonymous method?

查看:64
本文介绍了使用匿名方法定义backgroundworker的RunWorkerCompleted?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我使用了正确的术语

I Hope I used the right term

我想要的是这样的东西(我意识到它不能那样工作):

What I'm aiming for is something like this (I realise it doesn't work that way):

private bool someBool = false;

BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler(DoLengthyTask);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
    ()=>
        {
            someBool = true;
            Logger.Info("Finished");
        }
)

重要的部分是RunWorkerCompletedEventHandler,它在原始调用方的范围内定义,并且可以访问调用方的变量.

The important part being the RunWorkerCompletedEventHandler being defined within the scope of the original caller and by that having access to the caller's variables.

这可能吗?它会在someBool上产生可能的竞争条件吗?

Is this possible? Would it generate possible race conditions on the someBool?

推荐答案

在您的示例中它不起作用,因为完整的委托应接收2个参数:

It doesn't work in your example, since the complete delegate should receive 2 parameters:

private bool someBool = false;

BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler(DoLengthyTask);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
        (sender, e)=>
                {
                        someBool = true;
                        Logger.Info("Finished");
                }
)

这篇关于使用匿名方法定义backgroundworker的RunWorkerCompleted?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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