C# 在单独的线程中启动WPF窗口
我使用下面的代码在一个单独的线程中打开一个窗口C# 在单独的线程中启动WPF窗口,c#,wpf,multithreading,C#,Wpf,Multithreading,我使用下面的代码在一个单独的线程中打开一个窗口 public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); } private void button1_Click(object sender, RoutedEventArgs e) { Thread n
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Thread newWindowThread = new Thread(new ThreadStart(() =>
{
// Create and show the Window
Config tempWindow = new Config();
tempWindow.Show();
// Start the Dispatcher Processing
System.Windows.Threading.Dispatcher.Run();
}));
// Set the apartment state
newWindowThread.SetApartmentState(ApartmentState.STA);
// Make the thread a background thread
newWindowThread.IsBackground = true;
// Start the thread
}
}
如果我在方法中使用这段代码,它是有效的。但当我按如下方式使用它时,我会得到一个错误:
public partial class App : Application
{
#region Instance Variables
private Thread newWindowThread;
#endregion
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
newWindowThread = new Thread(new ThreadStart(() =>
{
// Create and show the Window
Config tempWindow = new Config();
tempWindow.Show();
// Start the Dispatcher Processing
System.Windows.Threading.Dispatcher.Run();
}));
}
private void button1_Click(object sender, RoutedEventArgs e)
{
// Set the apartment state
newWindowThread.SetApartmentState(ApartmentState.STA);
// Make the thread a background thread
newWindowThread.IsBackground = true;
// Start the thread
}
}
它抛出以下错误:
System.Threading.ThreadStateException
The state of the thread was not valid to execute the operation
原因是什么?为什么要这样做?几乎没有理由在应用程序中运行2EndUI线程。。。如果您想要一个非模态的新窗口,请实例化您的窗口并调用
show
为什么差一点?因为这是一个非常复杂的主题,除非你有足够的预算来开发这种行为,否则你可以不使用它。我相信问题在于你在
线程开始运行后设置了ApartmentState
尝试:
@d、 moncada,@JPVenson,@TomTom对不起大家,尤其是@d.moncada,您的回答让我意识到了我的真正错误,如果只运行一次,直到我的代码运行为止。但我真正的问题是,我试着在两个位置按下按钮,实际上我用一个计时器调用了一个方法,该方法的行为
private void button1_Click(object sender, RoutedEventArgs e)
现在我的问题的解决办法是你只点击过一次吗?(一个线程不能启动两次)-1。没有理由?你见过运行6个屏幕的金融交易应用程序吗?每个屏幕(一个窗口)有一个独立的消息泵真是太好了。对于单独窗口使用单独线程的好处是,所有“UI是单线程的”都适用于每个窗口basis,这有助于并行化。是的,这是有原因的——它们是边缘原因,我承认它们不适用于大多数项目,但试图这样做的人很可能是“我需要它”的人之一。大多数人甚至不知道这是可能的。@jpvenson这不是我的代码完整,我需要主窗口继续执行其他代码并抛出带有警告消息的窗口,并使用窗口而不是消息框,因为这个想法是显示一个带有大号字母和颜色strong的大窗口,只是“技能”问题。。。我在一家公司工作,我们处理千兆字节的数据,但只处理两个非常复杂的窗口,所有内容都处于非常高的性能水平(使用Threding,但不像“将所有内容放在线程中并快乐”^^)。如果你的应用程序真的需要一个线程来处理每一个UI呈现,你应该重新考虑/重构你的软件设计。如果需要复杂的UI呈现,可以在线程中创建/修改数据,然后让UI呈现。在90%的情况下,有一种更好的方法可以把东西放到线程中。@JPVenson:嗯,你可以建议chrome开发团队重构他们的代码,然后。。。chrome不仅每个UI使用一个线程,而且每个UI使用一个进程。依赖他人代码的良好行为并不是真正健壮的,也不是可持续的。除非你们公司的每个人都是f***g优秀程序员:)@JPVenson:我不知道Guillermo的应用程序的大小,但如果UI呈现良好,将来不会出现问题,那么就没有理由为UI运行STA,所以我同意你的看法。但是如果UI有我怀疑的性能,那么您可以使用STA线程。因此,我认为人们只是从其他网站复制代码,编写类似的应用程序。
private void button1_Click(object sender, RoutedEventArgs e)