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

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

问题描述

我想在后台线程中执行的进程密集型方法调用如下所示:

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

object.Method(paramObj, paramObj2);

这三个对象都是我创建的.现在,从我看到的初始示例中,您可以将一个对象传递给后台工作人员的 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 事件中检索参数.您还可以使用 DoWorkEventArgs 中的 Result 变量将参数从 DoWork 事件传递到 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天全站免登陆