Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using async to sleep in a thread without freezing [closed]

So I a label here (""). When the button (button1) is clicked, the label text turns into "Test". After 2 seconds, the text is set back into "". I made this work with a timer (which has an interval of 2000):

private void button1_Click(object sender, EventArgs e) {     label1.Text = "Test";     timer.Enabled = true; }  private void timer_Tick(object sender, EventArgs e) {     label1.Text = ""; } 

This works; however though, I am curious about making it work in an async method.

My code looks like this currently:

private void button1_Click(object sender, EventArgs e) {     label1.Text = "Test";     MyAsyncMethod(); }  public async Task MyAsyncMethod() {     await Task.Delay(2000);     label1.Text = ""; } 

This doesn't work though.

like image 908
jacobz Avatar asked Jun 01 '13 23:06

jacobz


People also ask

Is thread sleep asynchronous?

The amazing thing is that the Thread. sleep will not block anymore! It's fully async. And on top of that, virtual threads are super cheap.

Is Task delay better than thread sleep?

Use Thread. Sleep when you want to block the current thread. Use Task. Delay when you want a logical delay without blocking the current thread.

What happens when you call async method without await?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

Are async methods thread safe?

This code is not thread-safe. Whatever else may be true, InternalFireQueuedAsync is racy if called by multiple threads. If one thread is running the while loop, it may reach a point at which it is empty.


1 Answers

As I mentioned your code worked fine for me, But perhaps try setting your handler to async and running the Task.Delay in there.

private async void Button_Click_1(object sender, RoutedEventArgs e) {     label1.Text = "Test";     await Task.Delay(2000);     label1.Text = ""; } 
like image 118
sa_ddam213 Avatar answered Sep 21 '22 05:09

sa_ddam213