2012-04-23 39 views
0

我正在使用WPF。我使用Dispatcher在主xaml窗口中运行线程进程。用STA线程错误打开另一个xaml窗口

然后我得到这个错误打开另一WPF展示显示3D图像的结果:

{“调用线程必须为STA,因为许多UI组件都需要 这个”}

这是我如何开始一个新的窗口:在一些POS加入这个

void DisplayFormThread() 
{ 
    IResult result = _mainWindow.GetResult(); 
    ResultView resultView = new ResultView (result); 
    resultView.Show(); 
} 

我试图解决这个问题ts在stackoverflow但它没有帮助:

ThreadStart start = delegate() 
{ 
    DispatcherOperation op = Dispatcher.CurrentDispatcher.BeginInvoke(
     new delegateNewWindow(DisplayFormThread), DispatcherPriority.Background); 

     DispatcherOperationStatus status = op.Status; 
        while (status != DispatcherOperationStatus.Completed) 
        { 
          status = op.Wait(TimeSpan.FromMilliseconds(1000)); 
          if (status == DispatcherOperationStatus.Aborted) 
          { 
           // Alert Someone 
          } 
        } 

     }; 

// Create the thread and kick it started! 
Thread thread = new Thread(start); 
thread.SetApartmentState(ApartmentState.STA); 
thread.Start(); 

我该如何解决问题?

在此先感谢。

回答

3

原因是我们新创建的线程未启用以支持WPF窗口基础结构。特别是,它不支持Windows消息泵,您必须为新创建的窗口运行单独的调度程序。 Here is sample for this

2

WPF要求thred是STA型的,所以如果你想DisplayFormThread由STA被称为THEAD你必须做这样的事情:

Thread newThread = new Thread(new ThreadStart(DisplayFormThread)); 
newThread.SetApartmentState(ApartmentState.STA); 
newThread.Start(); 

STAThread是指“单线程单元”,这指的是当前(主)线程使用的线程模型。基本上,通过[STAThread]声明,其他应用程序将知道您的线程在发送数据时的策略。 STA模型是Windows线程/应用程序最常见的线程模型。您可以阅读更多关于Apartment State here的文章。

+0

感谢您的回答。我已经试过这个,因为我也在我的问题中加入了这个。但是,在新窗口中的结果未显示... – olidev 2012-04-23 08:58:03