Accessing UI controls in Task.Run with async/await on WinForms

后端 未结 6 1472
忘了有多久
忘了有多久 2020-11-29 04:57

I have the following code in a WinForms application with one button and one label:

using System;
using System.IO;
using System.Threading.Tasks;
using System.         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 05:05

    Why do you use Task.Run? that start a new worker thread (cpu bound), and it causes your problem.

    you should probably just do that:

        private async Task Run()
        {
            await File.AppendText("temp.dat").WriteAsync("a");
            label1.Text = "test";    
        }
    

    await ensure you will continue on the same context except if you use .ConfigureAwait(false);

提交回复
热议问题