首先,这里的
BeginInvoke仅仅指的是Delegate的BeginInvoke,而非Control的BeginInvoke。 Control的BeginInvoke是在本线程执行,即创建control的线程,Delegate的BeginInvoke会从ThreadPool中选择并开辟一个异步线程来执行任务。
BeginInvoke出的线程都是后台线程,可以理解界为IsBackground=true,当前台线程停止时会自动停止,而不论它本身是否已执行完成.
BeginInvoke出的线程都是后台线程,可以理解界为IsBackground=true,当前台线程停止时会自动停止,而不论它本身是否已执行完成.
delegate void asynEventHandler();
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Is ThreadPool {0}",Thread.CurrentThread.IsThreadPoolThread);
Console.WriteLine("Is IsBackground:{0}", Thread.CurrentThread.IsBackground);
Console.WriteLine("ID:{0}", Thread.CurrentThread.ManagedThreadId);
Console.ReadLine();
asynEventHandler handler = new asynEventHandler(Work.DoWork);
handler.BeginInvoke(null,null);
//如果想等待异步线程执行完成,
//可以使用EndInvoke来获取执行结果
handler.EndInvoke(null);
}
}
class Work
{
public static void DoWork()
{
try
{
StreamWriter sw = new StreamWriter("log", true);
sw.WriteLine(string.Format("Is ThreadPool {0}", Thread.CurrentThread.IsThreadPoolThread));
sw.WriteLine(string.Format("Is IsBackground:{0}", Thread.CurrentThread.IsBackground));
sw.WriteLine(string.Format("ID:{0}", Thread.CurrentThread.ManagedThreadId));
sw.WriteLine(string.Format("Thread name:{0}", Thread.CurrentThread.Name));
sw.WriteLine("aaaa");
sw.Close();
Thread.CurrentThread.Abort();
}
catch(Exception ex)
{
string msg = ex.Message;
}
}
}
当想显示控制异步线程时,可以在被调函数中使用Thread.CurrentThread获取该线程。或者粗暴的使用ThreadPool。