同时运行两个代码C# [英] Run two codes simultaneously c#
问题描述
我在正在开发的应用程序中遇到这种情况,我需要在同一时间同时做两件事,而我对此却有些挣扎.我正在开发相机应用程序,因此需要与LED同时触发相机以获取良好的图像.以下是我尝试过的选项.
I have this situation in an app I am developing where I need to do two things at exactly the same time and I am kind of struggling with it. I am developing a camera application and I need to trigger the camera at the same time as an LED in order to get a good image. The following are the options I have tried.
-
使用两个线程:
Use two threads:
Thread t1 = new Thread(
new ThreadStart(() =>
{
//trigger LED here
}));
Thread t2 = new Thread(
new ThreadStart(() =>
{
//trigger camera
}));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
在当前线程上触发灯光,在单独的线程上触发相机
Trigger the light on the current thread and the camera on a separate thread
Thread t = new Thread(
new ThreadStart(() =>
{
//trigger camera
}));
// trigger LED
t.Start();
t.Join();
在这两种情况下,在出现10张图像后,我都会出现反向闪烁,这意味着相机和LED不同步.我的问题是,有什么方法可以实现我想要做的事情.
In both cases, I get the back flickers after like 10 images which means the camera and LED are not synchronised. My question is, is there any way to achieve what I am trying to do.
谢谢.
推荐答案
如果您无法在硬件中解决此问题,这是我可以在Windows等非实时操作系统上想到的最佳方法:
If you can't solve this in hardware here is the best approach that I can think of on a non-realtime OS like Windows:
- 为两个动作中的每个动作启动一个线程
- 将其优先级提高为高"或实时",以确保他们立即将CPU上的其他任何事件清除
- 让他们等待
Barrier
.这样可以确保两个线程都已启动,并且在继续之前已在屏障处签入.这有助于减少时序抖动.它不能保证两个线程同时执行其硬件操作,但会有所帮助.
如果那没有帮助,我不知道会怎样.值得一试.该操作系统不保证实时执行,但是CPU速度超过3 GHZ时,您可以获得惊人的实时速度. 上下文切换可能需要3000个周期,即0.000001秒.因此,您绝对可以实现非常精确的计时.
If that does not help I don't know what would. It is worth a try though. The OS does not guarantee realtime execution but with CPU speeds north of 3 GHZ you can achieve amazing realtime speeds. A context switch might take 3000 cycles which is 0.000001 seconds. So you absolutely can achieve extremely accurate timings.
这篇关于同时运行两个代码C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!