using Microsoft.VisualStudio.Threading;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        

        JoinableTaskFactory joinableTask = new JoinableTaskFactory(new JoinableTaskContext());
        private void button1_Click(object sender, EventArgs e)
        {
            // 这种同步不会引发死锁,又不用将当前方法标记为异步方法,但会阻塞UI线程            
            var ret2 = joinableTask.Run(async () => await doWorkAsync());
            textBox1.Text= ret2;
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            // 官方推荐使用这种写法,不阻塞主线程,也不死锁
            var ret = await doWorkAsync();
            textBox1.Text = ret;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            // 这种同步调用异步方法,会阻塞主线程,导致死锁,UI界面卡住。
            var ret = doWorkAsync().Result;
            textBox1.Text = ret;
        }

        private async Task<string> doWorkAsync()
        {
            return await Task.Run(() => {
                Thread.Sleep(5000);
                return $"线程#{Environment.CurrentManagedThreadId}执行完成!";
            });
        }
    }
}

 

posted on 2023-01-30 10:40  zooz  阅读(189)  评论(0编辑  收藏  举报