2009-01-23 42 views
4

我正在研究一个多线程的Silverlight应用程序。无法杀死Silverlight中的工作线程

该应用程序有两个线程:Main/UI和后台工作线程。

UI线程应该能够杀死后台线程,就像这样:

private Thread executionThread; 

.... 

executionThread = new Thread(ExecuteStart); 
executionThread.Start(); 

.... 

executionThread.Abort(); // when the user clicks "Stop" 

最后一行抛出一个异常:

MethodAccessException:试图访问该方法失败:系统。 Threading.Thread.Abort()

任何想法?为什么我不能在Silverlight中中止一个线程?

感谢, 纳伊米

+0

这可能也是有帮助的:http://msdn.microsoft.com/en-us/magazine/cc765416.aspx – MichaelGG 2009-01-24 05:04:00

回答

6

而不是手动创建一个线程为此目的您可能要考虑使用BackgroundWorker类。

此类具有用于在WorkerSupportsCancellation = true时取消异步操作的功能。

查看关于如何在Silverlight中使用BackgroundWorker的full example的MSDN文章。

+0

BackgroundWroker要求工作线程不断检查取消。有没有办法立即强制工作线程存在? – ANaimi 2009-01-23 15:17:51

4

它的记录,看到Thread.Abort()

这件具有 性SecurityCriticalAttribute属性, 通过 的Silverlight 类库.NET框架将其限制于内部使用。 使用此成员的应用程序代码抛出 MethodAccessException。

您可以使用ManualResetEvent(一种线程安全通信方法)来指示后台线程停止。

实施例中的代码后台线程:

if (!shouldStop.WaitOne(0)) 
// you could also sleep 5 seconds by using 5000, but still be stopped 
// after just 2 seconds by the other thread. 
{ 
    // do thread stuff 
} 
else 
{ 
    // do cleanup stuff and exit thread. 
} 
0

由于Silverlight代码遇到互联网,其通常为不可信的,其执行是更受限制,因为戴维指出。 相反,在后台线程的规范类中实现布尔型​​退出标志,以便您可以引发此标志并使用Thread.Join()来代替。

+0

不建议使用布尔标志,这些并不是真正的线程安全。 – 2009-01-23 10:33:10