Reputation: 1155
When using System.Threading.Thread.Sleep(n)
, I understand that it blocks the thread of the program, which result in the program being inaccessible; eg: Not being able to click buttons, or bring up other forms.
So what my question is, is there any other alternative that I could use that would just pause my one method, but still allow me to use buttons, and open other forms and such?
The code that I am using is messy becuase I have been using System.Threading.Thread.Sleep(1500)
but here it is:
while(Reader.Read() != null)
{
ApplicationPort.WriteLine(line);
System.Threading.Thread.Sleep(1500);
}
Line is just a string that is bein updated earlier on the code, the rate that it updates is too fast for what I am trying to accomplish so I am trying to slow the program down by using Sleep
. And ApplicationPort, is just a SerialPort
This code is not allowing me to use other object while it is sleeping, so is there an alternative to this where I can still use the rest of my program while the while just the while
loop sleeps?
Upvotes: 1
Views: 391
Reputation: 4923
You could use a while loop and Application.DoEvents
Something like:
while(Reader.Read() != null)
{
ApplicationPort.WriteLine(line);
var endDate = DateTime.Now + TimeSpan.FromSeconds(1.5);
while (DateTime.Now() < endDate)
{
Application.DoEvents();
}
}
However this is "hacky" and you should be following ArsenMkrt's answer.
Upvotes: 2
Reputation: 103
I'd consider adding a timer to your app and print the line when the timer hits. This would not tie up your app.
An example here Timer
Upvotes: 1
Reputation: 50752
Run your method in separate thread, and you will be free to pause/resume as much as you want...
Take a look to the Thread class
Upvotes: 3