Reputation: 538
I'd like to open a window in a thread. I'd like to use the Thread class as you can see in my code:
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();
}
}}
It doesn't works well, because when i clicking the button1 (or button2) the window1 (or window2) showed for a moment... If you have any suggestion for solve my problem i could appreciate that!
Upvotes: 0
Views: 140
Reputation: 10226
Try this
Running on the Same UI Thread:
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();
}
Running on Two Different Threads:
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();
}
For more details take a look at WPF Threading Model
Upvotes: 2
Reputation: 5804
Just try with Task instead of using Thread
if (((Button)sender).Name == "button1")
{
Task.Factory.StartNew(() =>winshow1());
}
if (((Button)sender).Name == "button2")
{
Task.Factory.StartNew(() =>winshow2());
}
Upvotes: 0