views:

1174

answers:

3

Hello,

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

+2  A: 

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.
}
Davy Landman
A: 

Since Silverlight code comes across the Internet, it is generally untrusted, and its execution is more restricted, as Davy pointed out. Rather, implement a boolean exit flag in the class that is canonical for the background thread, so that you can raise this flag and use Thread.Join() instead.

boolean flag's are not recommended, those are not really threadsafe.
Davy Landman
+4  A: 

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.

Peter McGrattan
The BackgroundWroker requires the worker thread to constantly check for cancellation. Is there a way to immediately force the worker thread to exist?
ANaimi
I'd advise you not to pursue the notion of "forcing" the worker thread to exit. Cancelling the worker thread so it returns to the ThreadPool is the way to go.Using a volatile bool or a ManualResetEvent will not "force" cancellation more immediately than a BackgroundWorker.
Peter McGrattan