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

后端 未结 2 569
臣服心动
臣服心动 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:39

    First of all, say no to async void methods (Event handlers are exceptions) because exceptions thrown inside it will not be noticed. Instead use async Task and await it.

    private async void button1_Click(object sender, EventArgs e)// <--Note the async modifier
    {
        // almost 15 process
        foreach (var process in Processes)
        {
            // call a async method to process
            await ProcessObject(process);
        }
    }
    
    private async Task ProcessObject(ProcessViewModel process)// <--Note the return type
    {
        // my code is here with some loops
        await Task.Run(()=>
        {
            //Will be run in ThreadPool thread
            //Do whatever cpu bound work here
        });
    
        //At this point code runs in UI thread
        process.Progress++;
    
        // feedback to UI
        UpdateRow(process);
    }
    

    However, this will start only one task at a time, once that is done it will start next. If you want to start all of them at once you can start them and use Task.WhenAll to await it.

    private async void button1_Click(object sender, EventArgs e)// <--Note the async modifier
    {
         var tasks = Processes.Select(ProcessObject).ToList();
         await Task.WhenAll(tasks);
    }
    

提交回复
热议问题