需要暂停以允许使用C#中的数据 [英] Need a pause to allow for data in C#
问题描述
大家好,
我需要延迟才能允许设备通过串行端口进行响应(这与星期一询问的有关for循环未循环或似乎不响应的问题有关)我需要延迟以允许回复处理.我正在尝试使用下面详述的那种功能:
Hi All,
I need a delay I can call to allow for a device to respond over a Serial port (this is related to a question asked on Monday about a for loop not looping or appearing not to) I need a delay to allow for a reply to be processed. I was trying to use a function of the sort detailed below:
public int WaitForData(int NbDataToWait, int Timeout)
{
int timeWaited = 0;
int timeToWait = 1; // 1 ms
while (timeWaited < Timeout && MyCompPort.BytesToRead < NbDataToWait)
{
timeWaited += timeToWait;
System.Threading.Thread.Sleep(timeToWait );
}
return timeWaited;
}
从Romain Taillandier看来,这似乎锁定了表格,并导致Thread.Sleep或我的厚度过大而无法正确使用它.当您调用它时,我以预期的字节数(例如15)和超时的值(例如30(mS))给出了WaitForData(15,30).它需要一个值,因为它需要传递一个整数,因为它不是无效值,
from Romain Taillandier this appears to lock the form and cause a problem the way Thread.Sleep or am I being thick and not using it correctly. I read it as you call it with the number of bytes you are expecting say 15 and the value of time out say 30 (mS) giving WaitForData(15,30). It needs a Value as it''s needs an integer passed to it as it is not to a void,
int Value; // off up declarations
Value = WaitForData(15,30);
对吗?
我让自己感到迷惑的是它的一小部分效果.....
Glenn
right??
I am getting myself confused one miniute it works........
Glenn
推荐答案
首先,在处理Thread.Sleep
时,不会发生任何其他事情,包括数据到达.其次,睡眠持续时间为1几乎等于20-25毫秒的最小持续时间,因为调用和处理睡眠所花费的时间超过了1毫秒,更不用说CPU上的时钟了具有在短时间内睡眠的分辨率.
First, While your Thread.Sleep
is processing, nothing else can happen, including the arrival of data. Second, a Sleep duration of 1 is pretty much going to end up as a duration of a minimum oif 20-25 milliseconds because it takes longer that 1 millisecond to call and process sleep, not to mention the clock on the cpu doesn''t have the resolution to sleep for such a short period of time.
Thread.Sleep永远不要在UI线程(即主线程)上使用,因为它将阻止采取任何其他措施位置-鼠标单击,按键,计时器等.
而是设置 SerialPort.ReadTimeout [ ^ ]大约是您通常收到的整个邮件的两倍,并处理 SerialPort .DataReceived [ ^ ]和 SerialPort.ErrorReceived [ ^ ]活动.在收到的数据中,收集字符,直到获得完整的消息.如果您收到错误接收事件,那么您将不会收到完整的消息.
现在,您完全不必等待输入-您只需在数据到达时就可以使用它,就像其他Windows处理一样.
Thread.Sleep should never be used on the UI thread (ie, the main thread) as it will prevent any other actions taking place - mouse clicks, key presses, timers, etc.
Instead, set a SerialPort.ReadTimeout[^] to a period about twice what you would normally receive the whole message in, and handle the SerialPort.DataReceived[^] and SerialPort.ErrorReceived[^] Events. In the data received, collect the characters until you have a complete message. If you get the error received event, then you didn''t get the whole message.
Now, you don''t have to wait for input at all - you can just work with the data when it arrives, like other windows processing.
这篇关于需要暂停以允许使用C#中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!