I’m writing a program which samples data using serial ports. What I try to implement is a wait “loop” where I can wait several minutes and then fetch data from a serial port. While waiting, however, I fetch data from another serial port at a rate of 2Hz, this is done through timer_Elapsed events.
My problem is that as a new programmer in c# I do not know how to implement a good, reliable wait method. This is needed because I do not want anything to execute (apart from events) while waiting for next data sample. Things I have been looking at are;
private async void wait(int time)
{
var delay = Task.Run(async () =>
{
Stopwatch sw = Stopwatch.StartNew();
await Task.Delay(time);
sw.Stop();
return sw.ElapsedMilliseconds;
});
Debug.Write("Millisecs", delay.Result.ToString());
}
Which works poorly, because it is non-blocking and somehow messes up serial communication.
System.Threading.Thread.Sleep(120000);
Which freezes everythang
- Creating one more thread
Which doesn't seem to do me any good, because I still need to freeze the main thread in order to run the other one, making timer_Elapsed - events hard to process properly.
Sadly, unable to write anything better I run following;
while (ticks < 150)
{
Application.DoEvents();
}
(int ticks is count of timer_Elapsed events)
which forces me to disable most UI buttons, the form itself and also makes me really nervous while only consuming about 50% of CPU capacity, according to task manager. I simply need advice on what coding approach is suitable for my type of scenario.
Thank you for your time!
EDIT:
I'm running a WinForm app using only one form as my UI. The whole code is a nightmare and I will not post it here.
After a couple of tries following code did it for me;
public async Void myMethod()
{
await Task.Delay(2000);
doStuff();
}
It is really a very simple one, I do not know what went wrong last time I tried this approach.