C# Winforms: A thread that can control the UI and can “sleep” without pausing the whole program. How?

前端 未结 4 1874
-上瘾入骨i
-上瘾入骨i 2021-01-14 05:31

OK...

Looks like WinForms and Threading in the same program is something that I can\'t master easily.

I\'m trying to make a custom Numeric Up Down out of two

4条回答
  •  佛祖请我去吃肉
    2021-01-14 06:02

    If you are willing to download the Async CTP (or wait for C# 5.0) you can use the new async and await keywords to make for a really elegant solution.1

    public class YourForm : Form
    {
      private async void UpPictureBox_Click(object sender, EventArgs args)
      {
        await Task.Delay(500);
        timer1.Enabled = is_mouse_down;
      }
    
      private async void DownPictureBox_Click(object sender, EventArgs args)
      {
        await Task.Delay(500);
        timer1.Enabled = is_mouse_down;
      }
    }
    

    The await keyword in the code above will yield control back to the message loop while the delay task is executing. Execution will pick back up where it left off upon completion of that task. This is but one among many reasons why the new keywords are so wicked cool.


    1Note that the Async CTP uses TaskEx instead of Task.

提交回复
热议问题