1

我想将带有通用参数的 func 传递给 BackgroundWorker,但我偶然发现了如何在另一端强制转换和运行 func。

以下代码演示了我正在尝试做的事情。Execute请注意,我在所有方法中都有两个约束,BackgroundExecutionContextBackgroundExecutionResult,并且我需要能够采用多个泛型参数。

public static class BackgroundExecutionProvider 
{

    public static void Execute<TValue, TResult>(Func<TValue, TResult> fc) 
        where TValue: BackgroundExecutionContext 
        where TResult: BackgroundExecutionResult
    {
        var bw = new BackgroundWorker();
        bw.DoWork += new DoWorkEventHandler(Worker_DoWork);

        bw.RunWorkerAsync(fc);
    }

    public static void Execute<TValue, T1, TResult>(Func<TValue, T1, TResult> fc)
        where TValue : BackgroundExecutionContext
        where TResult : BackgroundExecutionResult
    {
        var bw = new BackgroundWorker();
        bw.DoWork += new DoWorkEventHandler(Worker_DoWork);

        bw.RunWorkerAsync(fc);
    }

    public static void Execute<TValue, T1, T2, TResult>(Func<TValue, T1, T2, TResult> fc)
        where TValue : BackgroundExecutionContext
        where TResult : BackgroundExecutionResult
    {
        var bw = new BackgroundWorker();
        bw.DoWork += new DoWorkEventHandler(Worker_DoWork);

        bw.RunWorkerAsync(fc);
    }

    private static void Worker_DoWork(object sender, DoWorkEventArgs e)
    {

        //  How do I cast the EventArgs and run the method in here?

    }

}

您能建议如何实现这一目标,或者可能采用不同的方法吗?

4

1 回答 1

2

使用闭包而不是尝试将值作为参数传递更容易:

public static void Execute<TValue, TResult>(Func<TValue, TResult> fc)
    where TValue : BackgroundExecutionContext
    where TResult : BackgroundExecutionResult
{
    var bw = new BackgroundWorker();
    bw.DoWork += (_, args) =>
    {
        BackgroundExecutionContext context = GetContext(); //or however you want to get your context
        var result = fc(context); //call the actual function
        DoStuffWithResult(result); //replace with whatever you want to do with the result
    };

    bw.RunWorkerAsync();
}
于 2013-10-09T18:24:14.507 回答