C# async/await Progress event on Task<> object

前端 未结 4 1921
一个人的身影
一个人的身影 2020-12-02 17:22

I\'m completely new to C# 5\'s new async/await keywords and I\'m interested in the best way to implement a progress event.

Now I\'d prefer

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 17:42

    I had to piece together this answer from several posts as I was trying to figure out how to make this work for code that is less trivial (ie events notify changes).

    Let's assume you have a synchronous item processor that will announce the item number it is about to start work on. For my example I am just going to manipulate the content of the Process button, but you can easily update a progress bar etc.

    private async void BtnProcess_Click(object sender, RoutedEventArgs e)
    {       
        BtnProcess.IsEnabled = false; //prevent successive clicks
        var p = new Progress();
        p.ProgressChanged += (senderOfProgressChanged, nextItem) => 
                        { BtnProcess.Content = "Processing page " + nextItem; };
    
        var result = await Task.Run(() =>
        {
            var processor = new SynchronousProcessor();
    
            processor.ItemProcessed += (senderOfItemProcessed , e1) => 
                                    ((IProgress) p).Report(e1.NextItem);
    
            var done = processor.WorkItWorkItRealGood();
    
            return done ;
        });
    
        BtnProcess.IsEnabled = true;
        BtnProcess.Content = "Process";
    }
    

    The key part to this is closing over the Progress<> variable inside ItemProcessed subscription. This allows everything to Just works ™.

提交回复
热议问题