【发布时间】:2015-08-07 08:32:06
【问题描述】:
我为 Random 类创建了一个扩展方法,它在随机时间执行 Action(无效委托):
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(),会出现什么并发症?有替代品吗?
【问题讨论】:
标签: c# multithreading sleep