简体   繁体   English

在主线程中执行Task延续的方法

[英]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. 我必须创建一个类似于ContinueWith() ,但是将在主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的状态,并在完成时开始继续执行,但是我认为它不能以这种方式工作:

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 . 尝试传递“主”线程的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. 假设“主”线程是UI线程。 If it's not, then grab that thread's dispatcher after you make it. 如果不是,那么请在创建线程之后获取该线程的调度程序。 Use that dispatcher instead of Application.Current 's (ie CurrentDispatcher ). 使用调度Application.Current代替Application.Current的调度Application.Current (即CurrentDispatcher )。

You can create an ExtensionMethod for a process like this. 您可以为这样的过程创建ExtensionMethod 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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