有一个无线循环的线程需要时时接收数据,如下:
class EventClass
{
public event EventHandler Event_ReceDatasDone;
bool isCouldReceDatas = false;
public void StartReceDatas()
{
isCouldReceDatas = true;
System.Threading.ThreadPool.QueueUserWorkItem(a => {
while(true)
{
if(isCouldReceDatas==false)
{
return;
}
Event_ReceDatasDone?.Invoke(this, EventArgs.Empty);
}
});
}
public void StopReceDatas()
{
isCouldReceDatas = false;
}
}
class Program
{
static void Main(string[] args)
{
EventClass ec = new EventClass();
ec.Event_ReceDatasDone += (sender, arg) => {
for(int i=0;i<30;i++)
Console.WriteLine(DateTime.Now.ToString("mm:ss.fff")+" 收到数据");
};
ec.StartReceDatas();
System.Threading.Thread.Sleep(1000);
ec.StopReceDatas();
Console.ReadKey();
}
}
但是每次调用StopReceDatas()都不能立即结束线程,改为.net 的协作取消线程后就没问题了,协作取消线程代码如下:
class EventClass
{
public event EventHandler Event_ReceDatasDone;
CancellationTokenSource cancellationTokenSource;
public void StartReceDatas()
{
cancellationTokenSource = new CancellationTokenSource();
System.Threading.ThreadPool.QueueUserWorkItem(a => {
while(true)
{
if(cancellationTokenSource.IsCancellationRequested)
{
return;
}
Event_ReceDatasDone?.Invoke(this, EventArgs.Empty);
}
});
}
public void StopReceDatas()
{
cancellationTokenSource.Cancel();
}
}
class Program
{
static void Main(string[] args)
{
EventClass ec = new EventClass();
ec.Event_ReceDatasDone += (sender, arg) => {
for(int i=0;i<30;i++)
Console.WriteLine(DateTime.Now.ToString("mm:ss.fff")+" 收到数据");
};
ec.StartReceDatas();
System.Threading.Thread.Sleep(1000);
ec.StopReceDatas();
Console.ReadKey();
}
}
在取消一个执行时间很长的线程时,最好用微软自己的协作式取消线程机制,可以立即结束线程