使用 Func 和 Action 创建后台工作者 class

Creating a background worker class with Func and Action

嗨,我创建这个 class 是为了让我可以轻松地在后台做一些工作,但是我正在努力让它工作

public static class UtilityHelper
{
    private static void AssignWork<T>(this BackgroundWorker bw, Func<T> work, Action<T> completionWork = null)
    {
        bw.DoWork += new DoWorkEventHandler(delegate(object obj, DoWorkEventArgs args)
            {
                args.Result = work.Invoke();
            });
        if(completionWork != null)
        {
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delegate(object obj, RunWorkerCompletedEventArgs args)
            {
                completionWork.Invoke((T)args.Result);
            });
        }
    }

    public static void RunWorkAsync<T>(Func<T> work, Action<T> completionWork = null)
    {
        BackgroundWorker worker = new BackgroundWorker();
        worker.AssignWork<T>(work, completionWork);

        worker.RunWorkerAsync();
    }

    ...
}

我希望能够调用 UtilityHelper.RunWorkAsync 将方法作为动作和函数传入。 RetrieveKnownPrinters 方法 returns DataTable 和 UpdateDataViewWithKnownPrinters 方法有一个 DataTable 参数。

我想这样称呼它 UtilityHelper.RunWorkAsync<DataTable>(() => RetrieveKnownPrinters(), () => UpdateDataViewWithKnownPrinters());

但是我收到错误 Error 110 Delegate 'System.Action' does not take 0 arguments because Action of T takes one argument 但是如果我只使用 Action,我不能通过 .Invoke 传递参数。谁能帮我解决这个问题?

不能在Invoke()方法中传递参数。似乎您需要做的只是正确调用您的方法(注意 p):

UtilityHelper.RunWorkAsync<DataTable>(
        () => RetrieveKnownPrinters(), (p) => UpdateDataViewWithKnownPrinters(p));

编辑:你也可以试试这个

UtilityHelper.RunWorkAsync<DataTable>(
        RetrieveKnownPrinters, UpdateDataViewWithKnownPrinters);