Easy way to excecute method after a given delay?

前端 未结 2 1427
清酒与你
清酒与你 2021-02-03 13:20

Is there a easy way to perform a method after a given delay like in iOS out of the box?

On iPhone I would do this:

[self performSelector:@selector(connectS

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-03 14:12

    You can use a BackgroundWorker like so:

        private void Perform(Action myMethod, int delayInMilliseconds)
        {
            BackgroundWorker worker = new BackgroundWorker();
    
            worker.DoWork += (s, e) => Thread.Sleep(delayInMilliseconds);
    
            worker.RunWorkerCompleted += (s, e) => myMethod.Invoke();
    
            worker.RunWorkerAsync();
        }
    

    The call into this method would look like this:

    this.Perform(() => MyMethod(), 2500);
    

    The background worker will run the sleep on a thread off of the UI thread so your application is free to do other things while the delay is occurring.

提交回复
热议问题