Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the recommended way to pass data back and forth between two threads using C#

Tags:

c#

I am trying to make an app that will pass data between two servers Connection1 and Conenction2 using sockets.What i would like to do is receive data from Connection1 and pass it to Connection2 and vice-versa.Connection1 and Conenction2 are on different threads. What is the best way to call methods on different threads in order to pass data back and forth between them.Both threads will use the same message object type to communicate in both directions between them.

Thanks

like image 535
kenalex Avatar asked Jan 19 '26 08:01

kenalex


1 Answers

You should use immutable data transfer objects.

As long as a simple object is deeply immutable (meaning that neither it nor any of it's properties can change), there is nothing wrong with using it on multiple threads.

To pass the instances between threads, you might want to use a pseudo-mutable thread-safe stack. (This depends on your design)

like image 77
SLaks Avatar answered Jan 20 '26 21:01

SLaks