4

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

ANaimi
  • 6,266
  • 7
  • 32
  • 32

3 Answers3

6

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 McG
  • 18,857
  • 8
  • 45
  • 53
  • The BackgroundWroker requires the worker thread to constantly check for cancellation. Is there a way to immediately force the worker thread to exist? – ANaimi Jan 23 '09 at 15:17
  • 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 McG Jan 24 '09 at 03:10
  • Unfortunately there are certain cases where calling built-in functions might take a very long time, and they don't have a timeout mechanism. So the only way to stop them would be to call Thread.Abort. For example, the Regex class... http://stackoverflow.com/questions/9460661/implementing-regex-timeout-in-net-4 Note however that the only time you can use Thread.Abort without security exceptions is when you're running a Silverlight 5 application in elevated trust. – Steve Wortham Jul 06 '12 at 15:14
4

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
  • 15,109
  • 6
  • 49
  • 73
0

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.