ice88 <ia*********@nt lworld.com> wrote:
I would like to execute some code when a thread terminates, in the
context of that thread - I guess similar to an ExitThread handler - is
it possible in a C# .NET application?
I can see a way to execute code when a thread is thrown away - by
having per-thread static attributes that are themselves objects, when
the thread object associated with that static value is garbage
collected, the destructor for the object is driven - but that happens
on another thread, I need the execution to happen on the thread that
is ending (because I'm going to make a call to unmanaged code to clear
up some things which the unmanaged code has associated with the
thread)...
I would like to believe that the framework does provide for a 'thread
is about to be deleted' class, which implements some interface - but I
cannot find it - unless IDisposable does it?
It strikes me that the easiest way of doing this in a general way would
be something like:
public delegate void ThreadFinish();
public class ThreadStarterWi thFinish
{
public event ThreadFinish Finish;
ThreadStart starter;
public ThreadStarterWi thFinish (ThreadStart starter)
{
this.starter = starter;
}
public void Run()
{
try
{
starter();
}
finally
{
if (Finish != null)
{
Finish();
}
}
}
public void StartThread()
{
new Thread (new ThreadStart(Run )).Start();
}
}
Here's a test program to demonstrate its use:
public class Test
{
static void Main()
{
ThreadStarterWi thFinish tswf = new
ThreadStarterWi thFinish (new ThreadStart(Nor mal));
tswf.Finish += new ThreadFinish (OnFinish);
tswf.StartThrea d();
}
static void Normal()
{
Console.WriteLi ne ("Normal");
}
static void OnFinish()
{
Console.WriteLi ne ("OnFinish") ;
}
}
For a non-general solution, just put a try/finally block in the
appropriate ThreadStart-compatible method.
--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too