简体   繁体   中英

C# button click, show image and then exit

I have been programming a button_Click event, where I need the following:

  1. Set visibility of a gif to true (in picture box, was false at first)
  2. Wait one second with the picture shown (its a gif and I need it moving, which means System.Threading.Thread.Sleep(1000) will stop the animation)
  3. Exit program

I have this:

private void button1_Click(object sender, EventArgs e)
    {
        loading.Visible = !loading.Visible;
        // pause for a second, then exit
        Environment.Exit(0);
    }

Thanks!

You may use the following:

//      ↓↓↓↓↓ << notice the `async` keyword.
private async void button1_Click(object sender, EventArgs e)
{
    loading.Visible = !loading.Visible;
    // Wait for one second.
    await Task.Delay(TimeSpan.FromSeconds(1));
    Application.Exit();
}

The Task.Delay() method does the following:

Creates a task that will complete after a time delay.

And using the await keyword, we asynchronously wait for the task to complete. "asynchronously" means that the current thread (the UI thread in this case) will not be blocked. Therefore, the animation will not be affected.

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