Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法在Silverlight中终止工作线程_C#_.net_Silverlight_Multithreading - Fatal编程技术网

C# 无法在Silverlight中终止工作线程

C# 无法在Silverlight中终止工作线程,c#,.net,silverlight,multithreading,C#,.net,Silverlight,Multithreading,我正在开发一个多线程的Silverlight应用程序 该应用程序有两个线程:Main/UI和一个后台工作线程 UI线程应该能够杀死后台线程,如下所示: private Thread executionThread; .... executionThread = new Thread(ExecuteStart); executionThread.Start(); .... executionThread.Abort(); // when the user clicks "Stop" 最后

我正在开发一个多线程的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中中止线程

谢谢, Naimi

有文档记录,请参见

这个成员有一个 SecurityCriticalAttribute属性, 这就限制了它的内部使用 Silverlight的.NET框架 类库。应用程序代码 使用此成员抛出 MethodAccessException

您可以使用(线程安全通信方法)向后台线程发出停止的信号

后台线程中的示例代码:

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.
}

正如Davy所指出的,由于Silverlight代码是通过互联网传输的,所以它通常不受信任,而且它的执行受到更多的限制。
相反,在后台线程规范的类中实现布尔退出标志,这样您就可以提高这个标志并使用Toel.Con()代替.< /P>

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

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


请参阅MSDN上的这篇文章,了解如何在Silverlight中使用BackgroundWorker。

不建议使用布尔标志,因为它们不是真正的线程安全。BackgroundRoker要求工作线程不断检查取消。有没有办法立即强制工作线程存在?我建议您不要追求“强制”工作线程退出的概念。取消工作线程以使其返回到线程池是一种方法。与BackgroundWorker相比,使用volatile bool或ManualResetEvent不会立即“强制”取消。不幸的是,在某些情况下,调用内置函数可能需要很长时间,而且它们没有超时机制。所以阻止它们的唯一方法是调用Thread.Abort。例如,Regex类。。。但是请注意,只有在提升信任的情况下运行Silverlight 5应用程序时,才可以使用Thread.Abort而不出现安全异常。这也可能有帮助: