是否需要同步.NET SerialPort写入/读取? [英] Is it necessary to synchronize .NET SerialPort writes/reads?

查看:116
本文介绍了是否需要同步.NET SerialPort写入/读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我使用.NET SerialPort类读取和写入数据。读取是使用DataReceived事件完成的,我在内部假设是在ThreadPool线程上。编写是通过UI线程(WinForms)完成的。

In my application I use the .NET SerialPort class for reading and writing data. The reading is done using the DataReceived event, I assume internally on a ThreadPool thread. The writing is done by the UI thread (WinForms).

我在想,是否有必要同步对SerialPort实例的访问,以便没有读取/写入可以同时发生。我的良心告诉我,应该对这些调用进行锁定,但是我感到困惑,因为我在Internet上找到的所有C#SerialPort示例都根本没有使用锁定。

I was wondering, if it's necessary to synchronize the access to the SerialPort instance, so that no Reads/Writes can happen at the same time. My conscience tells me I should put locks around these calls, but I'm puzzled as all C# SerialPort examples I find on the Internet don't use locking at all.

推荐答案

以下是该主题的一个很好的话题,SerialPort类的作者也参与其中:

Here's a great thread on the topic, with the author of the SerialPort class participating:

MSDN:SerialPort如何处理接收到的数据?

根据我的经验,我编写了十几个用作硬件模拟器的串行通信应用程序,我没有锁定。当时我还不知道自己是否安全,但是实际上,我还没有出现错误。 (一年中,有20多个测试人员和自动测试机几乎不断使用它)也就是说,我的应用程序并没有离开公司,如果我正在编写供公众消费的应用程序,我可能会格外小心。

From my experience, I've written a dozen serial communication apps for use as hardware simulators, I don't lock. I didn't know at the time if I was safe or not, but in practice, I haven't had an error yet. (a year of near constant use by 20+ testers and automated test machines) That said, my applications don't leave the company, if I were writing apps for public consumption I might take more care.

这篇关于是否需要同步.NET SerialPort写入/读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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