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

时间:2016-09-27 16:16:58

标签: c# generics action func

您好我已经创建了这个课程,以便让我在后台做一些工作但是我很难让它工作

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方法返回DataTable,UpdateDataViewWithKnownPrinters有一个DataTable参数。

我想把它称为UtilityHelper.RunWorkAsync<DataTable>(() => RetrieveKnownPrinters(), () => UpdateDataViewWithKnownPrinters());

然而我收到错误错误110委托&#39; System.Action&#39;不接受0参数,因为T的Action接受一个参数但是如果我只使用Action,我就不能用.Invoke传递参数。任何人都可以帮我这个吗?

1 个答案:

答案 0 :(得分:0)

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

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

编辑:您也可以尝试这个

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