Wait for a while without blocking main thread

前端 未结 8 998
慢半拍i
慢半拍i 2020-12-01 20:50

I wish my method to wait about 500 ms and then check if some flag has changed. How to complete this without blocking the rest of my application?

相关标签:
8条回答
  • 2020-12-01 21:06

    It the method in question is executing on a different thread than the rest of your application, then do the following:

    Thread.Sleep(500);
    
    0 讨论(0)
  • 2020-12-01 21:08

    You can use await Task.Delay(500); without blocking the thread like Sleep does, and with a lot less code than a Timer.

    0 讨论(0)
  • 2020-12-01 21:11
    System.Threading.Thread.Sleep(500);
    

    Update

    This won't block the rest of your application, just the thread that is running your method.

    0 讨论(0)
  • 2020-12-01 21:17

    Asynchron Task:

     var task = new Task (() => function_test()); task.Start();
    
    public void function_test() { `Wait for 5000 miliseconds`   Task.Delay(5000);` }
    
    0 讨论(0)
  • 2020-12-01 21:19

    Using a timer should do the trick

    if you need to use a thread then here is an example

    void Main()
    {
        System.Threading.Thread check= new System.Threading.Thread(CheckMethod);
        check.Start();
    }
    
    private void CheckMethod()
    {
         //Code
         Thread.Sleep(500);
    }
    
    0 讨论(0)
  • 2020-12-01 21:24

    I don't really understand the question.

    If you want to block before checking, use Thread.Sleep(500);

    If you want to check asynchronously every x seconds, you can use a Timer to execute a handler every x milliseconds.

    This will not block your current thread.

    0 讨论(0)
提交回复
热议问题