I'm trying to share data between two applications: the first gets the data continuously from a sensor, all I need to do is to transmit these data while I'm receiving them to another (WPF) application (and draw a graph).
The data is received through an EventHandler, and then it's transmitted through a socket, like this:
static TcpClient client = new TcpClient("localhost", 8181);
static double w, dba;
static void Write()
{
try
{
Stream s = client.GetStream();
StreamReader sr = new StreamReader(s);
StreamWriter sw = new StreamWriter(s);
sw.AutoFlush = true;
while (true)
{
String line = "W:" + w + "DB/A:" + dba;
sw.Write(line);
Console.WriteLine(sr.ReadLine());
}
s.Close();
}
finally
{
client.Close();
}
}
The thing is, do I need to put it in a separate Thread? (As I tried to, unsuccessfully) Because like this, while the eventHandler keeps being triggered and producing data (storing it into the two variables), the sw seems unable to proceed.
Sorry if the question is a bit vague, it's my first attempt with a distributed app so I'm a bit confused as well.. any advice or help would be very appreciated!
TIA
Use memory mapped files, which allows you to directly share memory between applications. It will be significantly faster than most other approaches.
Look at the section called Non-Persisted Memory-Mapped Files, which details how to share a segment of memory via a string name. I use this in an application I worked on for debugging purposes, and it's fast enough that my C# application could read my native application's memory in real-time.
If you're transmitting the data via this method, consider how you would transmit data in general. Determine a polling frequency (say every 100ms) and have application A write the data to the memory-mapped file. Then have application B read that memory mapped file and store it locally in a collection. This is your transmission.
So A basically writes and rewrites the same structure into the memory mapped file and B reads it at a given polling rate and stores what it polls in a collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With