110,536
社区成员
发帖
与我相关
我的任务
分享
[DllImport("winmm")]
public static extern uint timeGetTime();
public static ManualResetEvent _mre = new ManualResetEvent(false);
private static Object thisLock = new object();
Thread th1;
Thread th2;
Thread th3;
Thread th4;
Thread th;
private void button1_Click(object sender, EventArgs e)//button1是开始按钮,单机开始采集数据
{
th1 = new Thread(getdata);
th1.Start();
th2 = new Thread(getdata);
th2.Start();
th3 = new Thread(getdata);
th3.Start();
th4 = new Thread(getdata);
th4.Start();
th = new Thread(timer);
th.Start();
}
void timer()
{
int t = 0;
int Millisecond = 100; //时钟触发间隔为100ms
while (t < 100) //定时器触发100次后自动结束
{
_mre.Reset();
uint timerstart = timeGetTime();
uint i = 0;
while (i < Millisecond)
{
i = timeGetTime() - timerstart;
}
timerstart = timeGetTime();
_mre.Set();
t = t + 1;
}
th1.Abort(); //销毁线程
th2.Abort(); //销毁线程
th3.Abort(); //销毁线程
th4.Abort(); //销毁线程
th.Abort(); //销毁线程
}
void getdata()
{
int nowtimes = 0;
while (nowtimes < 100)
{
Form1._mre.WaitOne();
lock (thisLock)
{
GetValue(); //从传感器获取数据
SaveValue(); //数据保存,将采集的数据保存到csv文本中
nowtimes = nowtimes + 1;
}
}
}
List<Task> tasks;
....
tasks.Add(Task.Run(()=>{
do1();
do2();
}));
结果[] temp= await Task.WhenAll(tasks);
这样的比较现代的更结构化的代码。当有编程设计效率高10倍的异步并发代码时,没有人喜欢研究诡异的信号量同步。 GetValue(); //从传感器获取数据
SaveValue();
连续测试10次,你能每一次都准确的到500个结果吗?slim=slim(3) //下异步锁,并限制最大次数
采集调度()
{
CancelToken //这个我们不清楚你环境,需不要需要设置超时,强制退出,就自己看着办了
await slim.asynwait(); //异步锁,保证你前面有3个在运行,后面一个先等着
for(i t0 100)
{
结果[] temp= await Task.WhenAll(采集数据1,采集数据2) //他们可以异步并行
}
//这里100次并行采集结束。至于保存其实可以延后。所以这里另外启动一个save task。或者干脆直接用TaskCompletionSource丢给外面,让外面自己决定怎么处理他
slim.释放();
}
task<结果> 采集数据1()
{
}
task<结果> 采集数据2()
{
}