对新的STAThread执行操作

时间:2015-03-11 19:49:15

标签: c# wpf

如何在新创建的STAThread上执行window.Close()之类的操作? 这是我目前的代码:

    Thread thread = new Thread(() =>
    {
        gameCanvas = new GameCanvas(width, height);

        SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher));

        gameCanvas.Closed += (s,e) => Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);

        Dispatcher.Run();
    });

    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();

我该如何执行gameCanvas.close(); 我真的不知道我已经尝试过Dispatcher.Invoke但我得到的对象没有设置引用等等错误

当前项目是一个Console项目,没有其他STAThread

1 个答案:

答案 0 :(得分:2)

您需要在初始线程可访问的位置存储对线程Dispatcher的引用。您可以为Dispatcher本身使用变量,或者更好的是,为WPF Window使用变量,因为它具有相关Dispatcher的成员属性,因为这可能更多对你有用。

我使用名为Window的股票WPF MainWindow创建了一个模仿您的设置的示例。此示例运行大约15秒,然后调用close。请注意,windowLock锁定对象仅用于安全访问window变量。

static void Main(string[] args)
{
    Object windowLock = new object();
    MainWindow window = null;

    Thread thread = new Thread(() =>
    {
        Dispatcher workerDispatcher = null;
        SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher));

        workerDispatcher = Dispatcher.CurrentDispatcher;

        lock (windowLock)
        {
            window = new MainWindow();
        }
        window.Closed += (s, e) => Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
        window.Show();

        Dispatcher.Run();
    });

    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();

    Thread.Sleep(15000);

    lock (windowLock)
    {
        if (null != window) // Highly unlikely, but not impossible.
        {
            window.Dispatcher.Invoke(() =>
            {
                window.Close();
            });
        }
    }
}