Wait for a while without blocking main thread

前端 未结 8 999
慢半拍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:25

    Thread.Sleep(500) will force the current thread to wait 500ms. It works, but it's not what you want if your entire application is running on one thread.

    In that case, you'll want to use a Timer, like so:

    using System.Timers;
    
    void Main()
    {
        Timer t = new Timer();
        t.Interval = 500; // In milliseconds
        t.AutoReset = false; // Stops it from repeating
        t.Elapsed += new ElapsedEventHandler(TimerElapsed);
        t.Start();
    }
    
    void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("Hello, world!");
    }
    

    You can set AutoReset to true (or not set it at all) if you want the timer to repeat itself.

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

    I've recently been struggling with the same issue where I needed an action to be run on schedule without blocking the UI.

    Here's my solution:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        RunOnSchedule(interval, cancellationToken);
    }
    
    private void RunOnSchedule(int interval, CancellationToken cancellationToken)
    {
        // Start the task you want to run on schedule
        TaskToRunOnSchedule(args);
        Task.Run(async () => 
        {
            // This loop checks if the task was requested to be cancelled every 1000 ms
            for (int x = 0; x < interval; x+=1000)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }
    
                await Task.Delay(1000);
            }
        }).GetAwaiter().OnCompleted(() =>
        {
            // Once the task for delaying is completed, check once more if cancellation is requested, as you will reach this point regardless of if it was cancelled or not.
            if (!cancellationToken.IsCancellationRequested)
            {
                // Run this method again
                RunOnSchedule(interval, cancellationToken);
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题