Async/Await with a WinForms ProgressBar

后端 未结 3 763
天命终不由人
天命终不由人 2020-12-08 22:12

I\'ve gotten this type of thing working in the past with a BackgroundWorker, but I want to use the new async/await approach of .NET 4.5. I may be barking up the wrong tree.

3条回答
  •  一生所求
    2020-12-08 22:32

    @StephenCleary's answer is correct. Though, I had to make a little modification to his answer to get the behavior what I think OP wants.

    public void GoAsync() //no longer async as it blocks on Appication.Run
    {
        var owner = new Win32Window(Process.GetCurrentProcess().MainWindowHandle);
        _progressForm = new Form1();
    
        var progress = new Progress(value => _progressForm.UpdateProgress(value));
    
        _progressForm.Activated += async (sender, args) =>
            {
                await Go(progress);
                _progressForm.Close();
            };
    
        Application.Run(_progressForm);
    }
    

提交回复
热议问题