【发布时间】:2017-04-08 01:19:31
【问题描述】:
按照规范,我构建了一个监视某些资源的应用程序。现在我有一个主窗口,当事件发生时会发出警报,说明规范必须是一个颜色鲜艳的大窗口。 我对问题的解决方法如下
private void StatusChanges(Alarm m, EventArgs e)
{
//Compares two 32-bit signed integers for equality and, if they are equal, replaces one of the values.
if (Interlocked.CompareExchange(ref running, 1, 0) == 0)
{
newWindowThread = new Thread(new ThreadStart(() =>
{
try
{
// Create and show the Window
Alert tempWindow = new Alert();
tempWindow.Show();
//if (cancelRun)
// tempWindow.Close();
// Start the Dispatcher Processing
System.Windows.Threading.Dispatcher.Run();
}
catch (Exception)
{
throw;
}
finally
{
running = 0;
}
}));
// Set the apartment state
newWindowThread.SetApartmentState(ApartmentState.STA);
// Make the thread a background thread
newWindowThread.IsBackground = true;
newWindowThread.Start();
}
}
else
{
if (Interlocked.CompareExchange(ref running, 0, 1) == 1)
{
try
{
System.Windows.Threading.Dispatcher.FromThread(newWindowThread).InvokeShutdown();
Alert tempWindow = new Alert();
tempWindow.Close();
}
catch (Exception)
{
//throw;
MessageBox.Show("Todo esta ok");
}
}
//running = 0;
}
}
此方法由 Timer 每隔一段时间执行一次
我的目标是当警报结束时,移除警报窗口的过程,我使用了Thread.Abort();没用,有时程序抛出异常并显示没有Visual Studio in aplition发生在外面,尝试使用threa.Join ();但它没有用,直到
System.Windows.Threading.Dispatcher.FromThread use (newWindowThread) InvokeShutdown ().;
这至少停止了窗口的显示,但是当我创建时
Alert tempWindow = new Alert();
在初始化构造函数中
SoundPlayer player = new Sound ("../../Sounds/BOMB_SIREN-BOMB_SIREN-247265934.wav");
player.PlayLooping();
当我关闭窗口时
player.Stop();
现在如果没有,我会做下一个
Alert tempWindow = new Alert();
tempWindow.Close();
声音继续播放
我知道这不是最好的解决方案,但它确实有效。 我想给我您的意见,并就如何改进代码给我一些建议。
【问题讨论】:
-
不要创建多个 UI 线程。你这样做是把自己置身于一个受伤的世界。通过不这样做来避免整个情况。只有一个 UI 线程负责操作整个 UI。
-
@Servy 但是我如何在没有主窗口的情况下显示另一个窗口失去焦点
-
如果这是你的问题那么问那个问题,而不是所有这些。也就是说,如果您只想了解如何将焦点设置到给定窗口,您应该能够通过一些简单的研究找到该问题的答案。
-
@Servy 真的我的问题是我有一个运行我的主代码的窗口并且想要显示另一个窗口而没有主窗口的代码停止运行,即使我想在第二个窗口中执行操作不停止在主窗口中运行代码
-
您不应该在 UI 线程中运行 any 非 UI 代码。如果您有非 UI CPU 绑定的工作要做,那么您应该创建一个新线程并在那里完成工作,而不是在第二个 UI 线程中长时间运行 CPU 绑定工作时创建一个新的 UI 线程来显示 UI。使用 UI 线程更新 UI,使用非 UI 线程进行非 UI 工作。
标签: c# wpf multithreading