无法在Silverlight中杀死工作线程

时间:2009-01-23 10:11:45

标签: c# .net silverlight multithreading

我正在开发一个多线程Silverlight应用程序。

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

UI线程应该能够杀死后台线程,如下所示:

private Thread executionThread;

....

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

....

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

最后一行引发了一个异常:

  

MethodAccessException:尝试访问方法失败:System.Threading.Thread.Abort()

有什么想法吗?为什么我不能在Silverlight中中止一个帖子?

谢谢, 纳伊米

3 个答案:

答案 0 :(得分:6)

您可能需要考虑使用BackgroundWorker类,而不是手动创建线程。

此类具有内置功能,可在WorkerSupportsCancellation = true时取消异步操作。

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

答案 1 :(得分:4)

有记录,请参阅Thread.Abort()

  

该会员有一个   SecurityCriticalAttribute属性,   这限制了它的内部使用   Silverlight的.NET Framework   班级图书馆。应用程序代码   使用此成员抛出一个   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.
}

答案 2 :(得分:0)

由于Silverlight代码来自互联网,它通常是不受信任的,并且它的执行受到更多限制,正如Davy指出的那样。 相反,在类中实现一个布尔出口标志,该标志对于后台线程是规范的,因此您可以引发此标志并使用Thread.Join()代替。