相关疑难解决方法(0)

任务的延续(由async/await构建)在WPF应用程序的主线程上运行,但在控制台应用程序中的子线程上运行

假设我有一个简单的C#控制台应用程序:

class Program
{
    static async void func()
    {
        Thread.CurrentThread.Name = "main";
        await Task.Run(() =>
        {
            Thread.CurrentThread.Name = "child";
            Thread.Sleep(5000);
        });
        Console.WriteLine("continuation is running on {0} thread", Thread.CurrentThread.Name);
    }

    static void Main(string[] args)
    {
        func();
        Thread.Sleep(10000);
    }
}
Run Code Online (Sandbox Code Playgroud)

当5000毫秒通过时,我们看到"继续在子线程上运行"消息.当另一个5000毫秒通过时,主线程完成其工作并关闭应用程序.它看起来很合乎逻辑:异步任务及其延续在同一子线程上运行.

但现在假设我有一个简单的WPF应用程序:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    async private void mainWnd_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        Thread.CurrentThread.Name = "main";
        await Task.Run(() =>
        {
            Thread.CurrentThread.Name = "child";
            Thread.Sleep(5000);
        });
        this.Title = string.Format("continuation is …
Run Code Online (Sandbox Code Playgroud)

c# wpf asynchronous task async-await

1
推荐指数
1
解决办法
1586
查看次数

标签 统计

async-await ×1

asynchronous ×1

c# ×1

task ×1

wpf ×1