Вопрос

I would like to pass func with generic parameters to a BackgroundWorker but I'm stumbled upon on how to cast and run the func at the other end.

The following code demonstrates what I'm trying to do. Notice I have two constraints in all Execute methods, BackgroundExecutionContext and BackgroundExecutionResult, and I need to able to take more that one generic parameters.

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?

    }

}

Can you suggest how to achieve this or maybe with a different approach?

Это было полезно?

Решение

It's easier to just use a closure instead of trying to deal with passing the value as a parameter:

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();
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top