Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to kill a worker thread in Silverlight

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

like image 578
ANaimi Avatar asked Dec 31 '22 06:12

ANaimi


2 Answers

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.

like image 142
Peter McG Avatar answered Jan 01 '23 18:01

Peter McG


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.
}
like image 39
Davy Landman Avatar answered Jan 01 '23 20:01

Davy Landman