SerialPort等待响应 [英] SerialPort wait for response

查看:95
本文介绍了SerialPort等待响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET 4.0中是否有机会等待响应然后返回响应?

Do we have in .NET 4.0 the opportunity to wait for a response and then to return the response?

目前,我正在这样做,但这并不是很好,我也不喜欢:

Currently I'm doing it like this but it isn't really nice and I don't like it:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        byte[] options = new byte[]{1,1,0};
        COMManager mgr = new COMManager("COM1");

        byte[] result = mgr.GetResponse(options);
    }
}

和我的COM管理器类 (我必须在单独的类(dll)中进行操作):

And my COM Manager Class (I have to do the operation in a seperate class (dll)):

public class COMManager
    {
        SerialPort sp = null;
        byte[] result = null;
        bool completed = false;

        public COMManager(string comport)
        {
            sp = new SerialPort(comport);
            sp.DataReceived +=new SerialDataReceivedEventHandler(sp_DataReceived);
        }

        public byte[] GetResponse(byte[] option)
        {
            sp.Write(option, 0, option.Length);
            //I don't like the way...
            while (!completed) { }
            completed = false;
            return result;
        }

        void  sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            result = new byte[sp.BytesToRead];
            sp.Read(result, 0, sp.BytesToRead);
            completed = true;
        }
    }

在.NET 4.5中,我们可能有机会使用等待"语句.但是对于当前项目,我们仅允许使用.NET 4.0. 有什么想法吗?

In .NET 4.5 we may have the opportunity to use the "await" statement. But for the current project we only are allowed to use .NET 4.0. Any ideas?

推荐答案

对于您的原始问题,可以使用

For your original question, to block the executing thread you can use a ManualResetEvent or AutoResetEvent which will get Set when your response has been obtained. There's a fairly good explanation on the page.

对于线程来说,经验法则是,如果您对自己正在做的事情不太清楚,请不要这样做.

For threading, the rule of thumb is that if you're not extremely clear on what you're doing, don't do it.

访问事件时进行同步阻止似乎是一种浪费.考虑到数据是流,最终可能很难维护抽象.

Synchronous blocking when you have access to events seems like a waste. Considering that the data is a stream, this might end up being a hard to maintain abstraction.

您也可以与TaskCompletionSource异步进行此操作.您可以调用SetResult而不是进行设置,然后等待.Task,但是想法几乎是相同的.

You can also do this in async with TaskCompletionSource. Instead of set, you can call SetResult, and you await the .Task, but the idea is pretty much the same.

这篇关于SerialPort等待响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆