【问题标题】:Passing a method to a backgroundworker dowork将方法传递给后台工作人员 dowork
【发布时间】:2016-04-28 19:41:43
【问题描述】:

在下面的代码中,有没有一种方法可以代替总是订阅 updateWorker_DoWork 方法,而是传递一个这样的方法

public void GetUpdates(SomeObject blah)
{
    //...
    updateWorker.DoWork += new DoWorkEventHandler(blah);
    //...
}


public void GetUpdates()
{
    //Set up worker
    updateWorker.WorkerReportsProgress = true;
    updateWorker.WorkerSupportsCancellation = true;
    updateWorker.DoWork += new DoWorkEventHandler(updateWorker_DoWork);
    updateWorker.RunWorkerCompleted +=
        new RunWorkerCompletedEventHandler(updateWorker_RunWorkerCompleted);
    updateWorker.ProgressChanged +=
        new ProgressChangedEventHandler(updateWorker_ProgressChanged);

    //Run worker
    _canCancelWorker = true;
    updateWorker.RunWorkerAsync();
    //Initial Progress zero percent event
    _thes.UpdateProgress(0);
}

【问题讨论】:

    标签: c# backgroundworker


    【解决方案1】:

    对于您的RunWorkerAsync(),您可以传递您喜欢的任何参数。您可以将 Func()Action() 放入其中,然后在您的 DoWork() 中将对象转换回此特定类型并调用它。

    例如herehere

    private void InitializeBackgroundWorker()
    {
        _Worker = new BackgroundWorker();
    
        // On a call cast the e.Argument to a Func<TResult> and call it...
        // Take the result from it and put it into e.Result
        _Worker.DoWork += (sender, e) => e.Result = ((Func<string>)e.Argument)();
    
        // Take the e.Result and print it out
        // (cause we will always call a Func<string> the e.Result must always be a string)
        _Worker.RunWorkerCompleted += (sender, e) =>
        {
            Debug.Print((string)e.Result);
        };
    }
    
    private void StartTheWorker()
    {
        int someValue = 42;
    
        //Take a method with a parameter and put it into another func with no parameter
        //This is called currying or binding
        StartTheWorker(new Func<string>(() => DoSomething(someValue)));
    
       while(_Worker.IsBusy)
           Thread.Sleep(1);
    
       //If your function exactly matches, just put it into the argument.
       StartTheWorker(AnotherTask);
    }
    
    private void StartTheWorker(Func<string> func)
    {
        _Worker.RunWorkerAsync(func);
    }
    
    private string DoSomething(int value)
    {
        return value.ToString("x");
    }
    
    private string AnotherTask()
    {
        return "Hello World";
    }
    

    【讨论】:

    • 谢谢。那么如果我想将委托传递给 StartTheWorker 函数,参数类型会是什么。本质上,我希望能够调用 StartTheWorker(DoSomething) 并让 DoSomething 作为后台工作人员运行
    • @James:这只是用Func() 构建的另一个包装器。我更新了示例以反映这一点。
    【解决方案2】:

    如果我没有误会你,你需要 lambda 表达式来构造匿名方法。

    updateWorker.DoWork += (sender,e)=>
      {
          //bla
      }
    

    现在您不必总是编写方法并将其传递给new DoWorkEventHandler(myMethod)

    【讨论】:

      【解决方案3】:

      解决了,比我想象的要简单得多。只需为 DoWork 上调用的方法创建一个委托。可能应该更好地表达我最初的问题。

          public delegate void DoWorkDelegate(object sender,DoWorkEventArgs e);
      
           public void GetUpdates()
           {
               StartWorker(new DoWorkDelegate(updateWorker_DoWork));
           }
      
           public void StartWorker(DoWorkDelegate task)
           {
               //Set up worker
               updateWorker.WorkerReportsProgress = true;
               updateWorker.WorkerSupportsCancellation = true;
               updateWorker.DoWork += new DoWorkEventHandler(task);
               updateWorker.RunWorkerCompleted +=
                   new RunWorkerCompletedEventHandler(updateWorker_RunWorkerCompleted);
               updateWorker.ProgressChanged +=
                   new ProgressChangedEventHandler(updateWorker_ProgressChanged);
      
               //Run worker
               _canCancelWorker = true;
               updateWorker.RunWorkerAsync();
               //Initial Progress zero percent event
               _thes.UpdateProgress(0);
           }
      
            private void updateWorker_DoWork(object sender, DoWorkEventArgs e)
            {
                BackgroundWorker worker = sender as BackgroundWorker;
                e.Result = GetUpdatesTask(worker, e);
            }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多