Best way to create a “run-once” time delayed function in C#

前端 未结 12 1468
我在风中等你
我在风中等你 2020-12-13 08:54

I am trying to create a function that takes in an Action and a Timeout, and executes the Action after the Timeout. The function is to be non-blocking. The function must be

12条回答
  •  孤街浪徒
    2020-12-13 09:31

    This seems to work for me. It allows me to invoke _connection.Start() after a 15 second delay. The -1 millisecond parameter just says don't repeat.

    // Instance or static holder that won't get garbage collected (thanks chuu)
    System.Threading.Timer t;
    
    // Then when you need to delay something
    var t = new System.Threading.Timer(o =>
                {
                    _connection.Start(); 
                },
                null,
                TimeSpan.FromSeconds(15),
                TimeSpan.FromMilliseconds(-1));
    

提交回复
热议问题