开发者

Accessing a serial connection state within two threads

开发者 https://www.devze.com 2023-01-14 20:03 出处:网络
I\'m trying to set up another thread that currently checks the status of the object being referenced.

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 pro开发者_运维问答gram 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?


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号