是否需要同步.NET SerialPort 写入/读取?

发布于 2024-10-07 04:43:05 字数 239 浏览 0 评论 0原文

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

我想知道是否有必要同步对 SerialPort 实例的访问,以便不会同时发生读/写。我的良心告诉我,我应该对这些调用加锁,但我很困惑,因为我在 Internet 上找到的所有 C# SerialPort 示例根本不使用锁定。

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).

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

胡渣熟男 2024-10-14 04:43:05

这是关于该主题的一个很棒的主题,SerialPort 类的作者参与了:

MSDN:SerialPort 如何处理 DataReceived?

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

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

MSDN: How does SerialPort handle DataReceived?

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.

百善笑为先 2024-10-14 04:43:05

从文档中:

此类型 (SerialPort) 的任何公共静态(在 Visual Basic 中为共享)成员都是线程安全的。不保证任何实例成员都是线程安全的。

所以你应该明确地用锁来同步你的读/写。

From the documentation:

Any public static (Shared in Visual Basic) members of this type (SerialPort) are thread safe. Any instance members are not guaranteed to be thread safe.

So you should definetly synchronize your read/writes with locks.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文