开发者

C# Thread.Sleep() cause lag

Ok, i have problem in C#. In my script Threading.Sleep() cause lag, i think i'm doing something wrong, this is part of source:

case 2:
{
   mouse_event(MOUSEEVENTF_LEFTDOWN, Pos.X, Pos.Y, 0, 0);
   mouse_event(MOUSEEVENTF_LEFTUP, Pos.X, Pos.Y, 0, 0);

   SendKeys.Send(textBox1.Text);
   Thread.Sleep(300);
   SendKeys.Send("{ENTER}");

   break;
}

I want to send text, wa开发者_高级运维it for 300 milliseconds and send enter, but i just receive lag for that time and everything is done without waiting. Maybe there is something alternative to it?


What do you mean by lag? In this case without having much context it looks like you are blocking the main thread which it what then locks up your application for the duration of Sleep(). You also said you want to sleep for 300 milliseconds but you have 1000 passed to the function. Use something like a BackgroundWorker to put the logic for sending the text in a background thread so you don't block the UI while it's happening.


What do you mean by getting lag? I'm guessing this is how you are describing the time that your code is spending sleeping.

Perhaps you might want to look at a Timer class [0] that you can then bind the later code to as an event.

[0] Three timer classes are available described here: http://msdn.microsoft.com/en-us/magazine/cc164015.aspx. I tend to use the System.Timers.Timer class.


Edit in response to comment:

You need to think about what you mean by "do nothing". Doing nothing includes not updating the UI or anything. Literally do nothing. I'm assuming this is what you are describing as lag. To get around this there are the two methods described in the two answers. Both ultimately involve using threads so that the main thread can continue to allow the UI functionality can happen while your secondary thread can do work.

My method would involve a timer. When you want the program to stop for a bit you create a timer with an event that will fire at the end of your pause. That event then calls the method you want to run at the end of that time. This may require a bit of refactoring of your code.

The other method involves spawning a separate that your other code can run in. Becuase this is a secondary thread sleeping this will not effect the responsiveness of the rest of your application, just of that one thread so it shouldn't matter. This may well be the easiest way of doing things.

One thing is for sure though that if you aren't really very comfortable or familiar with how multiple threads in one application works then you might want to do some general reading first.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜