0

我有一个解析 html 文档的方法,但它需要很长时间并且 UI 冻结。所以我想使用一个线程,但我很困惑。线程有很多种,比如后台工作线程、调度程序等。我应该使用哪种类型的线程?另外,在我的方法中,我传递了一个参数。如果我使用线程,如何传递一个参数?

4

2 回答 2

0

自 WPF 以来,我不再使用后台工作程序。我听说它是​​为 WinForms 创建的,应该在 WPF 中避免使用,但是我可能弄错了。由于您将字符串作为参数传递(而不是某些 ui 控件),因此访问另一个线程应该没有问题,如下所示:

private void DoStuff(string documentName)
{
    Action a = () => 
    {
        var result = ParseFile(documentName);
        Action b = () => 
        {
            TextBox1.Text = result;
        };
        Dispatcher.BeginInvoke(b);
    };
    a.BeginInvoke(callback => 
    {
        a.EndInvoke(callback);
    }, null);
}

注意:不要将委托放入循环中,而是将循环放入委托中。

于 2012-07-25T10:48:50.643 回答
0

这是一个使用后台工作者的示例代码:

// I usually disable controls (buttons, etc.)
// so user is prevented to perform other
// actions
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s, e) =>
{
     // Get the parameter
     var param = e.Argument as <your expected object>
     // Perform parsing
}
worker.RunWorkerCompleted += (s1, e1) =>
{
     System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(
        new Action(() =>
        {
             // enable you controls here
        }));
}
worker.RunWorkerAsync(parameter);

希望这可以帮助!

于 2012-07-25T09:36:09.410 回答