相关疑难解决方法(0)

Async/Await与WinForms ProgressBar

我在过去使用BackgroundWorker得到了这种类型的东西,但是我想使用.NET 4.5的新async/await方法.我可能正在咆哮错误的树.请指教.

目标:创建一个组件,该组件将执行一些长时间运行的工作,并在执行工作时显示带有进度条的模态表单.该组件将获取窗口的句柄,以便在执行长时间运行的工作时阻止交互.

状态:请参阅下面的代码.在我尝试与windows进行交互之前,我以为自己做得很好.如果我把事情单独处理(即不要触摸!),一切都"完美"运行,但是如果我点击任一窗口,程序会在长时间运行结束后挂起.忽略实际交互(拖动),就好像UI线程被阻止一样.

问题:我的代码可以很容易修复吗?如果是这样,怎么样?或者,我应该使用不同的方法(例如BackgroundWorker)吗?

代码(Form1是带有ProgressBar和公共方法的标准表单,UpdateProgress,用于设置ProgressBar的值):

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Starting..");
        var mgr = new Manager();
        mgr.GoAsync();
        Console.WriteLine("..Ended");
        Console.ReadKey();
    }
}

class Manager
{
    private static Form1 _progressForm;

    public async void GoAsync()
    {
        var owner = new Win32Window(Process.GetCurrentProcess().MainWindowHandle);
        _progressForm = new Form1();
        _progressForm.Show(owner);

        await Go();

        _progressForm.Hide();
    }

    private async Task<bool> Go()
    {
        var job = new LongJob();
        job.OnProgress += …
Run Code Online (Sandbox Code Playgroud)

c# multithreading asynchronous winforms async-await

17
推荐指数
3
解决办法
2万
查看次数

标签 统计

async-await ×1

asynchronous ×1

c# ×1

multithreading ×1

winforms ×1