【发布时间】:2014-01-13 08:37:36
【问题描述】:
我有一个 WPF 应用程序,其中我有这个类:
public partial class Global : UserControl
{
public static List<Thread> listofthreads = new List<Thread>();
public Global()
{
InitializeComponent();
Thread windowThread = new Thread(delegate() { verifing(); });
listofthreads.Add(windowThread);
windowThread.Start();
}
public void verifing()
{
if (Global2.Pat_pathregfile.Length > 5 && Global2.Pat_pathcalibfile.Length > 5) {
if (utilisation.Dispatcher.CheckAccess())
{
utilisation.Visibility = Visibility.Visible;
}
else
{
utilisation.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
utilisation.Visibility = Visibility.Visible;
}));
}
foreach (Thread t in listofthreads) {
try
{
t.Suspend();
}
catch { }
}
}
else {
if (utilisation.Dispatcher.CheckAccess())
{
utilisation.Visibility = Visibility.Hidden;
}
else
{
utilisation.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
utilisation.Visibility = Visibility.Hidden;
}));
}
Thread windowThread = new Thread(delegate() { verifing(); });
windowThread.Start();
listofthreads.Add(windowThread);
}
}
}
我需要杀死properly我使用过的所有线程
foreach (Thread t in listofthreads) {
try
{
t.Suspend();
}
catch { }
}
但程序提示不推荐使用suspend方法。
- 为什么?
- 似乎有些线程在关闭窗口后仍在工作,为什么会出现这种情况?我该如何解决?
- wpf 中是否存在另一种杀死线程的方法?
【问题讨论】:
-
Suspend方法已被标记为过时。你应该使用ManualResetEvent 来同步线程。 -
更好地解释一下,你想达到什么目的。您对线程的使用和
Visibility的设置表明您做错了事。您是否尝试执行某种验证? -
你不想挂起一个线程。您希望将线程置于等待状态,或发出信号让线程自行终止。但是你不想挂起,也不想杀死一个线程。
标签: c# wpf multithreading thread-safety threadpool