c# 使用SynchronizationContext切换线程

private void Button_Click(object sender, RoutedEventArgs e)
{
    Console.WriteLine($"外部线程:{Thread.CurrentThread.ManagedThreadId}");

    var syncContext = SynchronizationContext.Current;

    Action<object> callback = new Action<object>(input => syncContext.Post(_ =>
    {
        Console.WriteLine($"线程结束:{Thread.CurrentThread.ManagedThreadId}");
    }, null));

    ThreadPool.QueueUserWorkItem(o =>
    {
        Console.WriteLine($"线程开始:{Thread.CurrentThread.ManagedThreadId}");
        callback?.Invoke(null);
    });

}
posted @ 2022-05-22 20:32  trykle  阅读(30)  评论(0)    收藏  举报