【问题标题】:How to write current thread task continuation that will execute after standard continuation worked? [closed]如何编写将在标准延续工作后执行的当前线程任务延续? [关闭]
【发布时间】:2013-04-30 13:45:32
【问题描述】:

我需要编写扩展方法,它可以像Task.ContinueWith() 一样工作,但在主线程上和Task.ContinueWith() 结束之后。

public static Task ContinueWithOnMainThread(this Task task, Action action) {
    return task.ContinueWith(t => action(), TaskScheduler.FromCurrentSynchronizationContext());
}

此方法有效,但在 Task.ContinueWith() 之前执行

我就是这样测试的:

public partial class MainWindow : Window {
    public MainWindow() {
        InitializeComponent();
        Loaded += delegate {
            LogThread("\nInMain ThredId: " + Thread.CurrentThread.ManagedThreadId);
            var task = new Task(InTask);
            task.ContinueWith(TaskContinue);
            task.ContinueWithOnMainThread(ReturnedToMainThread);
            task.Start();
        };
    }

    void InTask() {
        this.Dispatcher.Invoke(DispatcherPriority.DataBind, (Action<string>)LogThread, "\nInTask ThredId: " + Thread.CurrentThread.ManagedThreadId);
    }

    void TaskContinue(Task task) {
        this.Dispatcher.Invoke(DispatcherPriority.DataBind, (Action<string>)LogThread, "\nTaskContinue ThredId: " + Thread.CurrentThread.ManagedThreadId);
    }

    void ReturnedToMainThread() {
        LogThread("\nReturnedToMainThread ThredId: " + Thread.CurrentThread.ManagedThreadId);
    }

    void LogThread(string text) {
        TB.Text += text;
    }
}

【问题讨论】:

  • 您尝试过任何方法吗?请阅读FAQHow to Ask
  • 你的情况真的不清楚 - 你没有告诉我们你是如何使用这个的,或者你是如何诊断问题的。
  • 现在我的情况清楚了吗?

标签: c# .net multithreading task-parallel-library


【解决方案1】:

所以问题就在这里:

var task = new Task(InTask);
task.ContinueWith(TaskContinue);
task.ContinueWithOnMainThread(ReturnedToMainThread);

您将两个延续添加到同一个task。如果你想让ReturnedToMainThreadTaskContinue 之后运行,那么你需要继续运行TaskContinue 来传递给ContinueWithOnMainThread。你可以这样做:

var task = new Task(InTask);
task.ContinueWith(TaskContinue)
.ContinueWithOnMainThread(ReturnedToMainThread);

还值得注意的是ContinueWithOnMainThread 不会总是在主线程上运行延续。它将从添加延续时处于活动状态的上下文中运行延续。如果您从主线程添加延续(即使它正在运行的任务不在主线程中),那么您很好,但是如果您实际上从后台线程/上下文附加延续,那么它将运行在那个背景环境中。

【讨论】:

  • 感谢您的回答。你真的帮了我。
猜你喜欢
  • 1970-01-01
  • 2016-02-21
  • 2022-12-07
  • 2015-02-11
  • 2014-05-23
  • 2011-11-19
  • 2018-05-28
  • 2020-03-19
  • 2016-11-27
相关资源
最近更新 更多