I have been given a snippet of data in documentation I was given to receive data from a device.
The code below will only listen for 5 seconds and then the method would return and the program would terminate.
public void ListenForData()
{
...
DataReader r = new DataReader();
...
r.DataRead += delegate (Object sender, DataEventArgs e)
{
Console.WriteLine("Read: " + e.Data);
};
r.StartListening();
Thread.Sleep(5000);
r.Dispose();
}
I want to keep the method open (so I can continue listening to data) but I'm unsure on the proper way to do this. I've looked at responses like:
while(true)
{
//my code
Thread.sleep(0);
}
But I'm not sure that this is the optimal use case. I feel it would hog a lot of CPU and wasn't the true intended way to listen for that data.
So what other options do I have?
I think your DataReader
needs to be a field somewhere scoped to the duration of you needing to receive data. Something like this (assuming Windows application):
class MainForm : Form
{
DataReader dataReader;
void listenButton_Click(object s, EventArgs e)
{
this.dataReader = new DataReader();
this.dataReader.DataRead += delegate (Object sender, DataEventArgs e)
{
Console.WriteLine("Read: " + e.Data);
};
this.dataReader.StartListening();
}
void stopButton_Click(object s, EventArgs e)
{
this.dataReader.Dispose();
this.dataReader = null;
}
}
Or console:
static class Program
{
static DataReader dataReader;
static void Main(string[] args)
{
StartListen();
Console.WriteLine("Push enter to exit");
Console.ReadLine(); // wait for enter key to exit
StopListen();
}
static void StartListen()
{
dataReader = new DataReader();
dataReader.DataRead += delegate (Object sender, DataEventArgs e)
{
Console.WriteLine("Read: " + e.Data);
};
dataReader.StartListening();
}
static void StopListen()
{
dataReader.Dispose();
dataReader = null;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.