How to asynchronously wait for x seconds and execute something then?

前端 未结 8 855
深忆病人
深忆病人 2020-12-03 03:03

I know there is Thread.Sleep and System.Windows.Forms.Timer and Monitor.Wait in C# and Windows Forms. I just can\'t seem to be able to figure out how to wait fo

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 03:35

    your application hangs because you are invoking the 5 second sleep/wait on the main UI thread. put the sleep/wait/whatever action in a separate thread (actually System.Windows.Forms.Timer should do that for you) and when it completes invoke the action that turns some control green. remember to check InvokeRequired. here's a short sample (SetText can be called from another thread, if it is the call will instead be invoked on the main UI thread where the textbox is on):

    private void SetText(string text)
    {
    // InvokeRequired required compares the thread ID of the
    // calling thread to the thread ID of the creating thread.
    // If these threads are different, it returns true.
    if (this.textBox1.InvokeRequired)
    {    
        SetTextCallback d = new SetTextCallback(SetText);
        this.Invoke(d, new object[] { text });
    }
    else
    {
        this.textBox1.Text = text;
    }
    }
    

    I took the sample from here (well worth a read!).

提交回复
热议问题