How to provide a feedback to UI in a async method?

后端 未结 2 579
臣服心动
臣服心动 2020-12-19 05:08

I have been developing a windows forms project where I have a 10 tasks to do, and I would like to do this in a async way. These tasks will star when the user cl

2条回答
  •  难免孤独
    2020-12-19 05:31

    Sriram covered how to do the async/await in his answer, however I wanted to show you another way to update the progress on the UI thread using his answer as a base.

    .NET 4.5 added the IProgress interface and the Progress class. The built in Progress class captures the synchronization context, just like async/await does, then when you go to report your progress it uses that context to make its callback (the UI thread in your case).

    private async void button1_Click(object sender, EventArgs e)
    {
         var progress = new Progress(UpdateRow); //This makes a callback to UpdateRow when progress is reported.
    
         var tasks = Processes.Select(process => ProcessObject(process, progress)).ToList();
         await Task.WhenAll(tasks);
    }
    
    private async Task ProcessObject(ProcessViewModel process, IProgress progress)
    {
        // my code is here with some loops
        await Task.Run(()=>
        {
            //Will be run in ThreadPool thread
            //Do whatever cpu bound work here
    
    
            //Still in the thread pool thread
            process.Progress++;
    
            // feedback to UI, calls UpdateRow on the UI thread.
            progress.Report(process); 
        });
    }
    

提交回复
热议问题