2.5 C#视觉程序开发实例1----开始设计架构一个简单的程序
第一步目标:
1 IO交互:读取IO 并且显示
2 相机采集线程: In[0]上升沿,采集图像, 通知处理线程显示图片
3 图像处理线程: 接受信号,显示图像
1 显示布局
2 程序逻辑图
目标: 程序初始化时 ,开启4个线程
1 IO 交互线程
2 相机采集线程
3 相机处理线程
4 Timer现成
3 CreateThread 创建线程
3.1 创建线程名称和ResetEvent
// 程序退出标志
ManualResetEvent StopProgramEvent;
AutoResetEvent newImgEvent_thread;// 图像采集线程通知ImgProcess Event
// ImgProcess线程
public Task threadProcessCCD;
// 相机采集线程 IO扫描线程
public Task threadAcqCCD_0, IO_Thread;
3.2 创建线程
/// <summary>
/// 启动线程
/// remark:
/// </summary>
private void CreateThread() //启动线程
{
try
{
StopProgramEvent.Reset();
// Thread_Status();
// 必须开启的线程
threadAcqCCD_0 = new Task(() => ImgAcqRunCCD0(), TaskCreationOptions.LongRunning);
threadAcqCCD_0.Start();
IO_Thread = new Task(() => IO_Circle(), TaskCreationOptions.LongRunning);
IO_Thread.Start();
}
catch (Exception ex)
{
MessageBox.Show("Create Thread Error:" + ex.Message);
}
}
public Form_vision()
{
InitializeComponent();
bdDisplay_Runsets1.ResultVisible = false;
Form_vision_SizeChanged(this,null);
iO_Monitors1.Init(ref inputs,ref outputs);
// 创建线程
CreateThread();
timer1.Interval = 100;
timer1.Start();
}
4 创建4个线程函数
暂时内容为空
#region IO Thread
/// <summary>
/// IO_Circle
/// </summary>
private void IO_Circle()
{
while (true)
{
// readInputs
// writeOutputs
System.Threading.Thread.Sleep(20);
if (StopProgramEvent.WaitOne(0, true)) break;
}//end while
}
#endregion
#region ImgAcqRun Thread
/// <summary>
/// IO_Circle
/// </summary>
private void ImgAcqRunCCD0()
{
int n_trig0_cur=0, n_trig0_last=0;
while (true)
{
try
{
// 通过判断上升沿进行 相机采集
if (n_trig0_cur > 0 && n_trig0_last == 0) //判断上升沿触发
{
//相机采集
int nRet = 0;
if(nRet==0)
{
newImgEvent_thread.Set();
}
}
}//try
catch (Exception ex)
{
this.TopMost = false;
}
if (StopProgramEvent.WaitOne(0, true)) break;
n_trig0_last = n_trig0_cur;
System.Threading.Thread.Sleep(5);
}//end while
}
#endregion
#region ImgProcessRun Thread
/// <summary>
/// ImgProcessCCD0
/// remark: thread 图像process0
/// </summary>
private void ImgProcessCCD(int n_thread_index = 0)
{
ListViewItem DATA = new ListViewItem();
DateTime ts3 = DateTime.Now;
bool[] flag = new bool[100];
DateTime current = DateTime.Now;
while ( newImgEvent_thread.WaitOne()) //相机1&2都已经已拍照
{
// img process
if (StopProgramEvent.WaitOne(0, true)) break;
} //end while
return;
}
#endregion ImgProcessRun Thread
Timer1 定时器 主要目的 持续更新IO输入输出的状态
private void timer1_Tick(object sender, EventArgs e)
{
iO_Monitors1.update_status(true,true);
}
5 线程退出
private void StopThread() //停止线程
{
StopProgramEvent.Set();
}
private void Form_vision_FormClosing(object sender, FormClosingEventArgs e)
{
StopThread();
Task.WaitAll();
}