访问两个线程内的串行连接状态

发布于 2024-09-16 09:53:37 字数 147 浏览 7 评论 0原文

我正在尝试设置另一个线程来当前检查所引用对象的状态。

主线程是运行程序并处理串行连接状态的线程。

第二个线程需要访问连接状态以继续从缓冲区发送和接收命令。

这可以吗?

I'm trying to set up another thread that currently checks the status of the object being referenced.

The main thread is what runs the program and also handles the serial connection state.

The second thread needs to access the connection state to continue sending and receiving commands from the buffer.

Is this possible to do?

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

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

发布评论

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

评论(1

甲如呢乙后呢 2024-09-23 09:53:37

当然。控制串行设备的线程需要提供一个线程安全的只读属性,该属性会记住它读取的最后一个状态。另一个线程可以随时读取该属性。

这是一个简单的解决方案:

string lastReadState = "";
object StateLock = new Object();
string State { get { lock(StateLock) { return lastReadState; } } }

// Main thread working away...
lock (StateLock) { lastReadState = ReadCurrentState(); }

// Other thread working away...
string state = State;

编辑(看到评论后)

SomeStateClass lastReadState = new StateClass();
object StateLock = new Object();
SomeStateClass State { get { lock(StateLock) { return lastReadState; } } }

// Main thread figures out the new state information at some point...
lock (StateLock) { lastReadState = new StateClass { Prop1 = whatever, ... }; }

// Other thread uses the state
var relevantInfo = State.Prop1;

Sure. The thread controlling the serial device needs to provide a thread-safe read-only property which remembers the last state that it read. The other thread can than read that propery whenever it would like.

Here's a simple solution:

string lastReadState = "";
object StateLock = new Object();
string State { get { lock(StateLock) { return lastReadState; } } }

// Main thread working away...
lock (StateLock) { lastReadState = ReadCurrentState(); }

// Other thread working away...
string state = State;

Edit (after seeing the comments)

SomeStateClass lastReadState = new StateClass();
object StateLock = new Object();
SomeStateClass State { get { lock(StateLock) { return lastReadState; } } }

// Main thread figures out the new state information at some point...
lock (StateLock) { lastReadState = new StateClass { Prop1 = whatever, ... }; }

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