Replacing methods that use backgroundworker to async / tpl (.NET 4.0)

后端 未结 3 521
南旧
南旧 2021-02-02 16:33

My questions are many. Since I saw. NET 4.5, I was very impressed. Unfortunately all my projects are .NET 4.0 and I am not thinking about migrating. So I would like to simplify

相关标签:
3条回答
  • 2021-02-02 17:09

    How about encapsulating the code that is always the same in a reusable component? You could create a Freezable which implements ICommand, exposes a property of Type DoWorkEventHandler and a Result property. On ICommand.Executed, it would create a BackgroundWorker and wire up the delegates for DoWork and Completed, using the value of the DoWorkEventHandler as event handler, and handling Completed in a way that it sets its own Result property to the result returned in the event.

    You'd configure the component in XAML, using a converter to bind the DoWorkEventHandler property to a method on the ViewModel (I assume you've got one), and bind your View to the component's Result property, so it gets updated automatically when Result does a change notification.

    The advantages of this solution are: it is reusable, and it works with XAML only, so no more glue code in your ViewModel just for handling BackgroundWorkers. If you don't need your background process to report progress, it could even be unaware that it runs on a background thread, so you can decide in the XAML whether you want to call a method synchronously or asynchronously.

    0 讨论(0)
  • 2021-02-02 17:17

    You should just use the Task Parallel Library (TPL). The key is specifying the TaskScheduler for the current SynchronizationContext for any continuations in which you update the UI. For example:

    Task.Factory.StartNew(() =>
    {
        return ProcessMethod(yourArgument);
    })
    .ContinueWith(antecedent =>
    {
        UpdateView(antecedent.Result);
    },
    TaskScheduler.FromCurrentSynchronizationContext());
    

    Aside from some exception handling when accessing the antecedent's Result property, that's all there is too it. By using FromCurrentSynchronizationContext() the ambient SynchronizationContext that comes from WPF (i.e. the DispatcherSynchronizationContext) will be used to execute the continuation. This is the same as calling Dispatcher.[Begin]Invoke, but you are completely abstracted from it.

    If you wanted to get even "cleaner", if you control ProcessMethod I would actually rewrite that to return a Task and let it own how that gets spun up (can still use StartNew internally). That way you abstract the caller from the async execution decisions that ProcessMethod might want to make on its own and instead they only have to worry about chaining on a continuation to wait for the result.

    UPDATE 5/22/2013

    It should be noted that with the advent of .NET 4.5 and the async language support in C# this prescribed technique is outdated and you can simply rely on those features to execute a specific task using await Task.Run and then execution after that will take place on the Dispatcher thread again automagically. So something like this:

    MyResultType processingResult = await Task.Run(() =>
    {
        return ProcessMethod(yourArgument);
    });
    
    UpdateView(processingResult);
    
    0 讨论(0)
  • 2021-02-02 17:30

    A few months have passed, but could this help you?
    Using async/await without .NET Framework 4.5

    0 讨论(0)
提交回复
热议问题