将方法传递给BackgroundWorker.DoEvent C#

时间:2016-04-28 11:28:01

标签: c# backgroundworker

我目前正在尝试将常规功能作为匿名的BackgroundWorker的DoWork事件运行。我遇到的问题是该方法根本没有运行。我目前的代码如下: -

public class Worker
{
    BackgroundWorker worker;
    public Worker(Func<bool> action)
    {
        worker = new BackgroundWorker();
        worker.DoWork += (sender, e) => e.Result = action;
        worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
        this.action = action;
    }

    private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Console.WriteLine("Thread completed : "+ e.Result.ToString());
    }

    public void DoWork()
    {
        Console.WriteLine("worker thread: working...");
        worker.RunWorkerAsync();
        //Wait for worker to complete
        do { } while (worker.IsBusy);
    }
}

函数传递如下: -

Worker workerObject = new Worker(new Func<bool>(() => methodThatReturnsBool(param1, param2)));
Thread workerThread = new Thread(workerObject.DoWork);

workerThread.Start();

如何通过该方法并让它在后台工作程序中运行?

1 个答案:

答案 0 :(得分:2)

从它的外观来看,你只是将动作本身作为结果,而不是调用它。

worker.DoWork += (sender, e) => e.Result = action();

等待循环也可能导致问题。至少放一个

do {Thread.Yield();} while (worker.IsBusy);

在那里

或者使用更干净(没有忙碌等待)的方法:

public class Worker
{
    private BackgroundWorker _worker;
    private AutoResetEvent _event;
    private Func<bool> _action;

    public Worker(Func<bool> action)
    {
        _action = action;
        _event = new AutoResetEvent(false);
        _worker = new BackgroundWorker();
        _worker.DoWork += (sender, e) => 
        {
            try
            {
                e.Result = _action();
            }
            finally
            {
                _event.Set();
            }
        };
        _worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
    }

    private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Console.WriteLine("Thread completed : "+ e.Result.ToString());
    }

    public void DoWork()
    {
        Console.WriteLine("worker thread: working...");
        _worker.RunWorkerAsync();
        _event.WaitOne();
    }
}