0

我想在线程中打开一个窗口。正如您在我的代码中看到的那样,我想使用 Thread 类:

namespace WFPThreadin {

public partial class MainWindow : Window
{
    private static Window1 win1;
    private static Window2 win2;
    Thread tid1, tid2;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void gomb_Click(object sender, RoutedEventArgs e)
    {
        if (((Button)sender).Name == "button1")
        {
            tid1 = new Thread(new ThreadStart(MainWindow.winshow1));
            tid1.SetApartmentState(ApartmentState.STA);
            tid1.Start();
        }

        if (((Button)sender).Name == "button2")
        {
            tid2 = new Thread(new ThreadStart(MainWindow.winshow2));
            tid2.SetApartmentState(ApartmentState.STA);
            tid2.Start();
        }
    }

    public static void winshow1()
    {
        win1 = new Window1();
        win1.Show();
    }

    public static void winshow2()
    {
        win2 = new Window2();
        win2.Show();
    }

}}

它效果不佳,因为当我单击按钮 1(或按钮 2)时,窗口 1(或窗口 2)会显示片刻......如果您有任何解决我的问题的建议,我将不胜感激!

4

2 回答 2

2

试试这个

在同一 UI 线程上运行:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
             new Thread(() =>
            {
                Dispatcher.Invoke((Action)(() =>
                    {
                        Window2 w2 = new Window2();
                        w2.Show();
                    }));
            }).Start();

        new Thread(() =>
        {
            Dispatcher.Invoke((Action)(() =>
            {
                Window3 w3 = new Window3();
                w3.Show();
            }));
        }).Start();

 }

在两个不同的线程上运行:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {

Thread   _firstWindowThread = new Thread(new ThreadStart(CallWindow1));
        _firstWindowThread.SetApartmentState(ApartmentState.STA);
        _firstWindowThread.IsBackground = true;
        _firstWindowThread.Start();


Thread  _secondWindowThread = new Thread(new ThreadStart(CallWindow2));
        _secondWindowThread.SetApartmentState(ApartmentState.STA);
        _secondWindowThread.IsBackground = true;
        _secondWindowThread.Start();


  } 


  private void CallWindow1()
    {
        Window2 w2 = new Window2();
        w2.Show();
        System.Windows.Threading.Dispatcher.Run();
    }

    private void CallWindow2()
    {
        Window3 w3 = new Window3();
        w3.Show();
        System.Windows.Threading.Dispatcher.Run();
    }

有关更多详细信息,请查看WPF 线程模型

于 2013-09-06T07:25:00.737 回答
0

只需尝试使用 Task 而不是使用 Thread

 if (((Button)sender).Name == "button1")
    {
       Task.Factory.StartNew(() =>winshow1());
    }

    if (((Button)sender).Name == "button2")
    {
       Task.Factory.StartNew(() =>winshow2());
    }
于 2013-09-06T07:18:14.063 回答