简体   繁体   中英

How can I pause a loop (while, foreach, for, or otherwise) in C#?

Is there a way to pause a loop for a specified time without blocking? I don't want to use Thread.Sleep(xx). Is there a way to use a manual event, or dispatcher timer to pause the loop? I don't want to use thread.sleep because it blocks the thread and I don't want that.

EDIT:

what i want to do is similar to post here:

serialport responding to EventHandler, but not ReadExisting or ReadLine?

it's not answered there, so i've explained what i need to do here.

i cannot open the serial port and keep it open, i have to close it every time. so, what i want to do is hit first item in loop, open the comport, write to it, read from it, then close it. if you've ever used a mouse or bluetooth scanner with windows, you know that not every comport sends back a message all the time. so if a port doesn't send a message back, it has to time out. if a message isn't received in a short period of time, i need to move on.

i might hit the same port again with a different message if it didn't respond the first time around. when i do this, i get an error that the port is already open; and it is, because the loop just blew through the code and didn't pause enough.

thread.sleep just blocks the thread, along with the message the comport sends back to it, i don't know why, it just does. i'd rather not use thread.sleep.

when i loop through it, i want it to pause until i close the port, then start with next item in loop. that's the most important part.

is there a way to start the loop, spawn a method on a new thread, pause the loop that called it, wait for either a message back or a time limit, then have the loop continue when the other thread says so? thanks

EDIT

i used an AutoResetEvent. thanks for you help

If you pause something, that it is blocked by definition. Pausing one thread will certainly give control to other threads.

Unless you need something else INSTEAD of pausing?

What is PAUSING to you - maybe if you update your question...

I just figured out - maybe you want to pause and have the UI running - then do something like this (in each step of your loop):

int times = 100;
while (times > 0) 
{
    Application.DoEvents();
    Thread.Sleep(10);
    times--;
}

This will both have GUI respond to you and will slow your loop.

use a ManualResetEvent . It allows you to pause a thread until another thread signals to continue the execution.

In the provided link there is an example at the bottom where it is shown how to use it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM