I'm working on a multi-threaded Silverlight application.
The application has two threads: Main/UI and a background working thread.
The UI thread should be able to kill the background thread, like so:
private Thread executionThread;
....
executionThread = new Thread(ExecuteStart);
executionThread.Start();
....
executionThread.Abort(); // when the user clicks "Stop"
The last line raises an Exception:
MethodAccessException: Attempt to access the method failed: System.Threading.Thread.Abort()
Any idea? why i cannot abort a thread in Silverlight?
Thanks, Naimi
Rather than creating a Thread manually for this purpose you might want to consider using the BackgroundWorker class.
This class has built in functionality for cancelling the asynchronous operation when WorkerSupportsCancellation = true.
Have a look at this article on MSDN for a full example of how to use the BackgroundWorker in Silverlight.
It's documented, see Thread.Abort()
This member has a SecurityCriticalAttribute attribute, which restricts it to internal use by the .NET Framework for Silverlight class library. Application code that uses this member throws a MethodAccessException.
You could use a ManualResetEvent (a thread safe communication method) to signal the background thread to stop.
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With