Thread .join 的用法一例

在使用身份证读卡器时,要求

  1. 身份证读到身份证 就 停止线程.

  2. 关闭界面时会 自动停止调用读身份证的线程.这时候就需要用到 Thead.join 

例子如下:

Thread thread;
private void barButtonItem6_ItemClick(object sender, ItemClickEventArgs e)
{
ThreadStart threadStart = new ThreadStart(processData);
thread = new Thread(threadStart);
thread.Start();

this.barButtonItem6.Enabled = false;
}

bool run = true;
public void processData()
{
if ((iRetCOM == 1) || (iRetUSB == 1))
{
run = true;
while (run)
{
try
{
if ((iRetCOM == 1) || (iRetUSB == 1))
{

int authenticate = CVRSDK.CVR_Authenticate();
if (authenticate == 1)
{
int readContent = CVRSDK.CVR_Read_Content(4);
if (readContent == 1)
{
//this.label10.Text = "读卡操作成功!";
this.Invoke(new FillDataCallBack(FillData));
}
else
{
//this.label10.Text = "读卡操作失败!";
}
}
else
{
//MessageBox.Show("未放卡或卡片放置不正确");
}
}
else
{
MessageBox.Show("初始化失败!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

public delegate void FillDataCallBack();
public void FillData()
{}

private void ElderLyAddNew_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
this.run = false;

// 关建在这里 ,这句话说明 要求 thread 线程结束时才执行下面有的代码.  把 thread 对应的线程执行完后 才会向下执行.
thread.Join();
CVRSDK.CVR_CloseComm();
// this.Close();
}
catch (Exception ex)
{
// MessageBox.Show(ex.ToString());
}
}

原文地址:https://www.cnblogs.com/xiajing12345/p/5643419.html