Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 424
  • Last Modified:

how to call a shared resouce (Serial Port) from multiple threads in vb.net - best Practice

Hi Coding Experts,

I have several threads that need to occasionally query a serial port.  The threads are constantly running and so it's quite possible that more than one will try to query and send data via the Serial port at any one time.

Whats the best way (pattern?) to do this?  

If I get the threads to query the Port directly, then I expect there would be a conflict when they open the Serial Port.

In Java I could call a synchronized method on an Object, but I'm not sure in VB.net. Having said this, there may be a better way than that.

Thanks!
0
jmsjms
Asked:
jmsjms
  • 3
  • 2
1 Solution
 
Randy PooleCommented:
You could create a static class that handles this and stores the requests and sends/reads them as needed.  This way you are not having to open and close the port on each read/write.
0
 
jmsjmsAuthor Commented:
THanks Randy.  This sounds very interesting but I'm not familiar with static classes in vb.net.  COuld you give me an example of how to use one?
0
 
Randy PooleCommented:
Sorry in VB it is called shared, basically instead of making an instance of the class you can call routines or variable defined as shared in the base class itself.
Here is an example if you would like to read up on it:
http://visualbasic.about.com/od/quicktips/qt/shared_member.htm
0
 
jmsjmsAuthor Commented:
Right. OK. So I could set the SerialPort as a shared Variable in a class.  

Then I could instantiate a Class in the calling threads code whenever I need to communicate with the Port. But then a thread calling a method in the class will still not have exclusive access to the Serial port as it could be sending data out whilst another was using another instance to collect...

I dont think I can just setup a queue of actions as each thread has to wait for the method it calls to complete. (It needs to power off/on serial devices and wait whilst this process completes)
0
 
jmsjmsAuthor Commented:
I'm currently testing a structure as below:

Serial port is opened on the main thread.

Threads all instantiate a Class that handles the SerialPort communication,

This class has a shared lock.

When the thread wants to access the shared com port, it calls a method in the class.
The class's method then trys to obtain the lock.
If it can obtain the lock, it does the work, if not it waits until it can.

Seems to work but I've got to do more testing but it looks like the way to go.

THanks Randy
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now