Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

c# - Wait for n seconds, then next line of code without freezing form

Hi I am trying to find a method of waiting a number of milliseconds before moving to the next line of code,

I have looked into Thread.Sleep but this will freeze the main form, I would like this to remain active.

I tried timers and stopwatches and both freeze the main form when they should be posting to a console when they tick.

I couldn't find a way of using task.delay or background worker in the wait I wanted either.

Pseudo Code:

Wait 2 - 6 seconds
Log "waiting"
Log "waiting"
Log "waiting"
Stop Waiting - Run next line of code.

The methods I have tried just freeze up the form and fill the log afterwards, I just want a simple method of waiting without freezing the form and without having to deal with events being called which would mean the next line isn't run.

Any help would be awesome because I am still new to c# and its been driving me a bit mad :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The await keyword, in conjunction with Task.Delay makes this trivial.

public async Task Foo()
{
    await Task.Delay(2000);
    txtConsole.AppendText("Waiting...");
    DoStuff();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...