in C#.NET , I've written the following simple background worker thread:
public class MyBackgrounder
{
public delegate void dlgAlert();
public dlgAlert Alert;
public event EventHandler eventAlert;
Thread trd;
public void Start()
{
if (trd == null || trd.ThreadState == ThreadState.Aborted)
{
trd = new Thread(new ThreadStart(Do));
}
trd.IsBackground = true;
trd.Priority = ThreadPriority.BelowNormal;
trd.Start();
}
void Do()
{
Thread.Sleep(3000);
Done();
}
void Done()
{
if (Alert != null)
Alert();
if (eventAlert != null)
eventAlert(this, new EventArgs());
Kill();
}
public void Kill()
{
if (trd != null)
trd.Abort();
trd = null;
}
}
static class Program
{
[STAThread]
static void Main()
{
MyBackgrounder bg = new MyBackgrounder();
bg.eventAlert += new EventHandler(bg_eventAlert);
bg.Alert = jobDone;
bg.Start();
}
static void bg_eventAlert(object sender, EventArgs e)
{
// here, current thread's id has been changed
}
static void jobDone()
{
// here, current thread's id has been changed
}
}
It just waits for 3 seconds (does its job) and then raises an specified event or calls a delegate. there's no problem until here and everything works fine. But when i watch the 'Thread.CurrentThread.ManagedThreadId' , i see it's the background thread! maybe it's normal , but how can i prevent this behavior? if you test the 'System.Windows.Forms.Timer' component and handle its 'Tick' event , you can see that the 'Thread.CurrentThread.ManagedThreadId' has not been changed from main thread Id to anything else.
what can i do?
See Question&Answers more detail:os