Re: Thread termination
From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 02/28/04
- Next message: Jon Skeet [C# MVP]: "Re: Polymorphism in ASP.Net"
- Previous message: Jon Skeet [C# MVP]: "Re: Polymorphism in ASP.Net"
- In reply to: ice88: "Thread termination"
- Next in thread: ice88: "Re: Thread termination"
- Messages sorted by: [ date ] [ thread ]
Date: Sat, 28 Feb 2004 20:57:12 -0000
ice88 <ian_edwards@ntlworld.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 ThreadStarterWithFinish
{
public event ThreadFinish Finish;
ThreadStart starter;
public ThreadStarterWithFinish (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()
{
ThreadStarterWithFinish tswf = new
ThreadStarterWithFinish (new ThreadStart(Normal));
tswf.Finish += new ThreadFinish (OnFinish);
tswf.StartThread();
}
static void Normal()
{
Console.WriteLine ("Normal");
}
static void OnFinish()
{
Console.WriteLine ("OnFinish");
}
}
For a non-general solution, just put a try/finally block in the
appropriate ThreadStart-compatible method.
-- Jon Skeet - <skeet@pobox.com> http://www.pobox.com/~skeet If replying to the group, please do not mail me too
- Next message: Jon Skeet [C# MVP]: "Re: Polymorphism in ASP.Net"
- Previous message: Jon Skeet [C# MVP]: "Re: Polymorphism in ASP.Net"
- In reply to: ice88: "Thread termination"
- Next in thread: ice88: "Re: Thread termination"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|