简体   繁体   中英

Method that executes a continuation of a Task in the main thread

I have to create a method, that similar to ContinueWith() , but will execute continuation in main thread, after main Task.

How can I do that? I could endlessly checking the state of Task in my method, and when it finishes start continuation, but I think it couldn`t work in such way:

Task<DayOfWeek> taskA = new Task<DayOfWeek>(() => DateTime.Today.DayOfWeek);

Task<string> continuation = taskA.OurMethod((antecedent) =>
{
    return String.Format("Today is {0}.", antecedent.Result);
});
// Because we endlessly checking state of main Task
// Code below will never execute

taskA.Start(); 

So what I could do here?

Try passing around the "main" thread's Dispatcher . Example:

Task.Factory.StartNew(()=>
{
    // blah
}
.ContinueWith(task=>
{
    Application.Current.Dispatcher.BeginInvoke(new Action(()=>
    {
        // yay, on the UI thread...
    }
}

Assuming that the "main" thread is UI thread. If it's not, then grab that thread's dispatcher after you make it. Use that dispatcher instead of Application.Current 's (ie CurrentDispatcher ).

You can create an ExtensionMethod for a process like this. Here is an example implementation

static class ExtensionMethods
{
    public static Task ContinueOnUI(this Task task, Action continuation)
    {
        return task.ContinueWith((arg) =>
        {
            Dispatcher.CurrentDispatcher.Invoke(continuation);
        });
    }
}

Consume it like this.

Task run = new Task(() =>
{
    Debug.WriteLine("Testing");
});
run.ContinueOnUI(() =>
{
    Notify += "\nExecuted On UI"; // Notify is bound on a UI control
});
run.Start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM