使用Thread.Sleep()总是很糟糕吗? [英] Is it always bad to use Thread.Sleep()?

查看:761
本文介绍了使用Thread.Sleep()总是很糟糕吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为类Random创建了一个扩展方法,该方法在随机时间执行Action(无效委托):

I created an extension method for the the class Random which executes an Action (void delegate) at random times:

public static class RandomExtension
{
    private static bool _isAlive;
    private static Task _executer;

    public static void ExecuteRandomAsync(this Random random, int min, int max, int minDuration, Action action)
    {
        Task outerTask = Task.Factory.StartNew(() =>
        {
            _isAlive = true;
            _executer = Task.Factory.StartNew(() => { ExecuteRandom(min, max, action); });
            Thread.Sleep(minDuration);
            StopExecuter();
        });
    }

    private static void StopExecuter()
    {
        _isAlive = false;
        _executer.Wait();

        _executer.Dispose();
        _executer = null;
    }

    private static void ExecuteRandom(int min, int max, Action action)
    {
        Random random = new Random();

        while (_isAlive)
        {
            Thread.Sleep(random.Next(min, max));
            action();
        }
    }
}

它工作正常.

但是在此示例中使用Thread.Sleep()可以吗,或者通常不应该使用Thread.Sleep(),会发生什么并发症?有其他选择吗?

But is the use of Thread.Sleep() in this example okay, or should you generally never use Thread.Sleep(), what complications could occur ? Are there alternatives?

推荐答案

使用Thread.Sleep不好吗?如果您确实想挂起 thread ,通常不会.但是在这种情况下,您不想挂起线程,而是想挂起任务.

Is using Thread.Sleep bad? Generally not, if you really want to suspend the thread. But in this case you don't want to suspend the thread, you want to suspend the task.

因此,在这种情况下,您应该使用:

So in this case, you should use:

await Task.Delay(minDuration);

这不会挂起整个线程,而只是挂起您要挂起的单个任务.同一线程上的所有其他任务都可以继续运行.

This will not suspend the entire thread, but just the single task you want to suspend. All other tasks on the same thread can continue running.

这篇关于使用Thread.Sleep()总是很糟糕吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆