C# progressbar IsIndeterminate while execut a function

C# progressbar IsIndeterminate while exectue a function

我希望在执行某项功能时有一个不确定的进度条。问题是当函数运行时 UI 冻结直到结束所以我最终得到:

void Button1_Click(object sender, RoutedEventArgs e)
{
    progressBar1.IsIndeterminate = true;
    Task.Factory.StartNew(() =>
    {
            scrape();
    });
}

问题是,对于 backgroundworker,我的抓取功能没有触发。我只放了 scrape(); onclick 它工作得很好。 scarpe 是这样的:

void scrape()
{
    string url = "www.site.com";
    var web = new HtmlWeb();
    var doc = web.Load(url);

    foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//p[@class='bio']")) 
    {   
        //scrape things
    }

    progressBar1.IsIndeterminate = false;
}

进度条进入不确定状态,但 scrape() 未触发,进度条仍处于不确定状态。 有帮助吗?

你应该让你的抓取方法异步,然后在 button1_click 中等待它,并在 button1_click 方法中保留 progressBar1.IsIndeterminate = false; 调用,因为你不允许从另一个方法更改它线。

您可能在后台线程 运行 的代码中遇到异常。

要么通过注册来捕获你的异常 AppDomain.UnhandledException

或者更具体地说 UnobservedTaskException 类似于 UnhandledException 但特定于从任务抛出的异常。

或者使您的方法异步并等待 try catch 子句中的操作:

async void Button1_Click(object sender, RoutedEventArgs e)
{
    progressBar1.IsIndeterminate = true;
    try
    {
        await Task.Factory.StartNew(() =>
        {
           scrape();
        });
    }
    catch(AggregateException ae)
    {}
    finally
    {
         progressBar1.IsIndeterminate = false;
    }
}

您正在从另一个线程调用分配 属性。 WPF 做一些事情来防止这样的跨线程访问,以将所有 UI 逻辑保留在 UI 线程(主线程)中。如果需要,您可以使用 Dispatcher 从 UI 线程调用方法。您可以使用 myControl.Dispatcher.Invoke(MyMethod).

从任何控件访问调度程序

还可以检查您是否需要从调度程序调用方法。使用 if (myControl.Dispatcher.CheckAccess())。如果此值为真,则您在 UI 线程上,不需要从调度程序调用。