问题
I am making an application in C# which uses a winform as the GUI and a separate thread which is running in the background automatically changing things. Ex:
public void Run()
{
while(true)
{
printMessageOnGui("Hey");
Thread.Sleep(2000);
// Do more work
}
}
How would I make it pause anywhere in the loop, because one iteration of the loop takes around 30 seconds. So I wouldn't want to pause it after its done one loop, I want to pause it on time.
回答1:
ManualResetEvent mrse = new ManualResetEvent(false);
public void run()
{
while(true)
{
mrse.WaitOne();
printMessageOnGui("Hey");
Thread.Sleep(2000); . .
}
}
public void Resume()
{
mrse.Set();
}
public void Pause()
{
mrse.Reset();
}
回答2:
You should do this via a ManualResetEvent.
ManualResetEvent mre = new ManualResetEvent();
mre.WaitOne(); // This will wait
On another thread, obviously you'll need a reference to the mre
mre.Set(); // Tells the other thread to go again
A full example which will print some text, wait for another thread to do something and then resume:
class Program
{
private static ManualResetEvent mre = new ManualResetEvent(false);
static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(SleepAndSet));
t.Start();
Console.WriteLine("Waiting");
mre.WaitOne();
Console.WriteLine("Resuming");
}
public static void SleepAndSet()
{
Thread.Sleep(2000);
mre.Set();
}
}
回答3:
You can pause a thread by calling thread.Suspend
but that is deprecated. I would take a look at autoresetevent for performing your synchronization.
来源:https://stackoverflow.com/questions/2430930/how-to-pause-suspend-a-thread-then-continue-it