Window_Loaded事件线程错误中的后台线程

时间:2013-03-11 13:51:35

标签: c# wpf multithreading backgroundworker

我必须加载一个窗口,在Window_Loaded我必须加载一些变量并在Window上显示它。

private void Window_Loaded_1(object sender, RoutedEventArgs e)
{         
    BackgroundWorker worker = new BackgroundWorker();

    worker.DoWork += (o, ea) =>
    {
        try
        {
            //code to download some variables which will show on UI of Window Loading
        }
        catch (Exception ex)
        {
            //The calling thread cannot access this object because a different thread owns it.
        }
    };

    worker.RunWorkerCompleted += (o, ea) =>
    {

    };

    worker.RunWorkerAsync();
}

但我得到一个线程异常。有没有办法在DoWork的{​​{1}}上显示窗口上的变量值?

2 个答案:

答案 0 :(得分:4)

您应该在DoWork部分中检索所需的数据,然后将其分配给ea.Result,这将使其在RunWorkerCompleted部分中可用。

RunWorkerCompleted部分,您可以再次访问ea.Result,将对象转换回您在DoWork中指定的任何类型,并根据需要将数据应用于UI控件。< / p>

worker.DoWork += (o, ea) =>
{
    ea.Result = GetMyData();
};

worker.RunWorkerCompleted += (o, ea) =>
{
    var myData = (myDataType)ea.Result;

    // Assign myData as needed to UI components...
};

答案 1 :(得分:1)

您需要让Dispatcher安排您的代码在UI线程上执行并编组必要的参数。尝试这样的事情:

Dispatcher.Invoke(
    new Action<string>(() =>
    {
        // Access UI from here
    }),
    DispatcherPriority.Normal
);

虽然这(或类似的东西,因为这是记事本代码)将解决您的问题,您应该考虑在您的实现中使用MVVM模式。然后,您将能够对ViewModel进行更改(只更新数据),UI将相应更新。