在 C#.NET 中,我编写了以下简单的后台工作线程:
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
}
}
它只等待 3 秒(完成它的工作),然后引发指定事件或调用委托。直到这里没有问题,一切正常。但是当我观看“ Thread.CurrentThread.ManagedThreadId ”时,我看到它是后台线程!也许这很正常,但我怎样才能防止这种行为?如果您测试“ System.Windows.Forms.Timer ”组件并处理其“ Tick ”事件,您可以看到“ Thread.CurrentThread.ManagedThreadId ”没有从主线程 ID 更改为其他任何内容。
我能做些什么?