基本BackgroundWorker的用法与参数 [英] Basic BackgroundWorker usage with parameters

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

问题描述

我的过程密集型的方法调用看起来是这样的:

My process intensive method call that I want to perform in a background thread looks like this:

object.Method(paramObj, paramObj2);



这三个对象都是那些我已经创建。现在,从我看到最初的例子,你可以传递一个对象到一个BackgroundWorker的DoWork的方法。但我应该如何去这样做,如果我需要通过额外的参数到该对象,就像我在这里干什么?我可以在一个单一的对象,把这个包,并用它做的,但我认为这将是明智的让别人对这个输入。

All three of these objects are ones I have created. Now, from the initial examples I have seen, you can pass an object into a backgroundworker's DoWork method. But how should I go about doing this if I need to pass additional parameters to that object, like I'm doing here? I could wrap this in a single object and be done with it, but I thought it would be smart to get someone else's input on this.

推荐答案

您可以将任何物体插入的RunWorkerAsync这个对象调用的参数,然后从DoWork的事件中获取的参数。您也可以从DoWork的事件使用的DoWorkEventArgs结果变量的RunWorkerCompleted事件传递参数。

You can pass any object into the object argument of the RunWorkerAsync call, and then retrieve the arguments from within the DoWork event. You can also pass arguments from the DoWork event to the RunWorkerCompleted event using the Result variable in the DoWorkEventArgs.

    public Form1()
    {
        InitializeComponent();

        BackgroundWorker worker = new BackgroundWorker();
        worker.DoWork += new DoWorkEventHandler(worker_DoWork);
        worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

        object paramObj = 1;
        object paramObj2 = 2;

        // The parameters you want to pass to the do work event of the background worker.
        object[] parameters = new object [] { paramObj, paramObj2 };

        // This runs the event on new background worker thread.
        worker.RunWorkerAsync(parameters);
    }

    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        object[] parameters = e.Argument as object[];

        // do something.

        e.Result = true;
    }

    private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        object result = e.Result;

        // Handle what to do when complete.                        
    }

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

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