Failed to kill worker thread in Silverlight

I am working on a multi-threaded Silverlight application.

The application has two threads: Main / UI and background workflow.

The user interface thread should be able to kill the background thread, for example:

private Thread executionThread; .... executionThread = new Thread(ExecuteStart); executionThread.Start(); .... executionThread.Abort(); // when the user clicks "Stop" 

The last line throws an exception:

MethodAccessException: Method access attempt failed: System.Threading.Thread.Abort ()

Any idea? Why can't I interrupt the stream in Silverlight?

Thanks Naaya

+4
source share
3 answers

Instead of creating a stream manually for this purpose, you may need to use the BackgroundWorker class.

This class has built-in functions for canceling an asynchronous operation when WorkerSupportsCancellation = true.

Check out this MSDN article for a complete example on how to use BackgroundWorker in Silverlight.

+6
source

It is documented, see Thread.Abort ()

This member has a SecurityCriticalAttribute attribute, which limits its internal use of the .NET Framework for the Silverlight library class. The application code that this member uses is a MethodAccessException.

You can use ManualResetEvent (the method of communication with the stream) to signal to stop the background stream.

Example code in the background thread:

 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. } 
+4
source

Since Silverlight code is found over the Internet, it is generally not trusted, and its execution is more limited, as Davy noted. Rather, we implement a logical exit flag in the class, which is canonical for the background thread, so you can raise this flag and use Thread.Join () instead.

0
source

All Articles