我必须编写一个发送消息的dll并等待响应,然后它才能继续。 到目前为止,这可能是dll的一部分:
public async Task<bool> WaitForRxThread(int TimeOut)
{
bool res = await Task.Run(() => WaitForResult(TimeOut));
return res;
}
private bool WaitForResult(int TimeOut)
{
_Result = new byte[0];
int counter = 0;
double WaitTimeout = TimeOut + DateTime.Now.TimeOfDay.TotalMilliseconds;
while (!(DateTime.Now.TimeOfDay.TotalMilliseconds >= WaitTimeout))
{
counter++;
int BytesToRead = sPort.BytesToRead;
if (BytesToRead > 0)
{
byte[] Bytes = new byte[BytesToRead];
sPort.Read(Bytes, 0, BytesToRead);
Array.Resize(ref _Result, _Result.Length + BytesToRead);
Array.Copy(Bytes, 0, _Result, (_Result.Length - BytesToRead), BytesToRead);
if (ResultComplete(Bytes) == true)
{
return true;
}
}
}
return false;
}
public bool ResultComplete(byte[] TestData)
{
if (TestData.Length > 4)
{
return true;
}
else
{
return false;
}
}
为了测试该dll,我编写了一个控制台应用程序,例如
static void Main(string[] args)
{
RS obj = new RS();
obj.OpenComport();
obj.SendMessage("Hello");
Console.WriteLine("Message send");
var result = obj.WaitForRxThread(5000);
Console.WriteLine("Read thread executed");
result.Wait();
Console.WriteLine("Process result");
if (result.Result)
{
obj.GetResult();
Console.WriteLine("Result is : " + Encoding.ASCII.GetString(obj.GetResult()));
Console.WriteLine("Done");
Console.ReadLine();
}
else
{
Console.WriteLine("Result is false");
}
obj.CloseComport();
}
当我运行该应用程序并在超时期限内将数据发送到此应用程序时,我什么都没有。 BytesToRead为0。当我在行上设置断点
var result = obj.WaitForRxThread(5000);
将数据发送到应用程序并继续,我按预期接收数据 有人可以解释我做错了什么吗?