C# wait for a function to execute and delay

  1. How can I create a delay in C#.

I know Thread.Sleep(0) but it is blocking my GUI.

  1. Also I need to pause the execution of the normal flow until a function return a result.

What you really want is the async extensions in C# 5.0, but those are not here yet.

What you want to look at today is background workers as they do this sort of thing without blocking the GUI.

Do some research on Threading. As you will want to run this in a separate thread

What?! When is C# 5.0 dropping? It’s becoming a rat-race.

What I usually do if I need to disable my GUI while something is running is… I disable my GUI while something is running. =p

Just set your Form’s Enabled file to false when it starts and true when it’s ready to go again. That’ll disable your whole GUI.

Wouldn’t the application still appear to hang from the user’s point of view?

Well, when I do it it’s always initiated by user action, so since it disables the controls (visually too, grayed out) it seems like it should. It doesn’t just randomly “hang”. Before I had it disable and gray out it did, which is why I started disabling it.

When you do that, does Windows 7 leave the program alone, or does it still like to show its “searching for solution” window?

Ah, that.

Anything I know will take a long time, I set it up on a BackgroundWorker (or thread it properly, depending on the scale of the project) if I think it might make Windows think it’s hung. For example, I wrote a program a few weeks ago to process a ridiculous number of server logs into a database then build a cache to make analyzing the data quicker.

The disabling everything is only for the users’ benefit.

Ok, that’s what I was trying to get at.

thanks for your answers.

Seems that the solution is the “BackgroundWorker” and I searched for tutorials on Google and could work for me.

What about a ‘delay’ function like in C++, can be implemented in C# ?

Maybe Task<T> would be enough…

Task(TResult) Class (System.Threading.Tasks)

Thanks for getting me to spit out the right answer, Force Flow. =p I always forget that Windows gets a bit antsy with those things until it happens.

The best way I can think of to implement a delay without Windows freezing would be to create a background worker with a function that just has a while loop that loops until enough time has passed (so get the start time then loop until (start + delay >= now), then return.

If you wanted to it disable everything, just wrap the delay in with the Enabled = False/True statements.

You could also make it a bit more flexible by giving it a function to call when it was done delaying (to enable everything or something).

I was thinking on something similar, get the time, add one minute, then use a while loop until the actual time is equal with the starting time + delay.

I’m a newbie and I have some problems adding the delay. Can you help me with the code ?