Pedro Pedro - 17 days ago 5
C# Question

c# Thread.Sleep make program lag

Hello i have a program with the follow code

oSkype.CurrentUserStatus = TUserStatus.cusOnline;
Thread.Sleep(20);
oSkype.CurrentUserStatus = TUserStatus.cusDoNotDisturb;
Thread.Sleep(20);
oSkype.CurrentUserStatus = TUserStatus.cusAway;
Thread.Sleep(20);
oSkype.CurrentUserStatus = TUserStatus.cusInvisible;
Thread.Sleep(20);


For some reason when it is running the program lag but when i stop the lag stop.
The lag is not from the computer because another programs still running Wheel.
What can i do to stop the lag?

Answer

Your lag is probably caused by the fact that the UI cannot respond while the UI thread is sleeping. If using an async method fixing this is quite easy with Task.Delay. Task.Delay sets a timer to go off later and then the method resumes. This keeps the UI thread responsive:

oSkype.CurrentUserStatus = TUserStatus.cusOnline;
await Task.Delay(20);
oSkype.CurrentUserStatus = TUserStatus.cusDoNotDisturb;
await Task.Delay(20);
oSkype.CurrentUserStatus = TUserStatus.cusAway;
await Task.Delay(20);
oSkype.CurrentUserStatus = TUserStatus.cusInvisible;
await Task.Delay(20);