Pre*_*eli 6 c# multithreading azure-worker-roles
我有时会遇到以下形式的代码:
while (true) {
//do something
Thread.Sleep(1000);
}
Run Code Online (Sandbox Code Playgroud)
我想知道这是否被认为是好的或坏的做法,如果有任何替代方案.
通常我会在服务的主要功能中"找到"这样的代码.
我最近在windows azure worker角色的"运行"功能中看到了具有以下形式的代码:
ClassXYZ xyz = new ClassXYZ(); //ClassXYZ creates separate Threads which execute code
while (true) {
Thread.Sleep(1000);
}
Run Code Online (Sandbox Code Playgroud)
我假设有更好的方法来阻止服务(或天蓝色工作者角色)退出.有人对我有建议吗?
Dáv*_*aya 10
好吧,当你这样做时Thread.Sleep(1000),你的处理器浪费了很少的时间来唤醒并什么都不做.
你可以用CancelationTokenSource做类似的事情.
当你打电话时WaitOne(),它会等到收到信号.
CancellationTokenSource cancelSource = new CancellationTokenSource();
public override void Run()
{
//do stuff
cancelSource.Token.WaitHandle.WaitOne();
}
public override void OnStop()
{
cancelSource.Cancel();
}
Run Code Online (Sandbox Code Playgroud)
这样可以防止Run()方法退出,而不会在忙碌的等待中浪费你的CPU时间.
另一种方法可能是使用AutoResetEvent并实例化默认情况下发出的信号。
public class Program
{
public static readonly AutoResetEvent ResetEvent = new AutoResetEvent(true);
public static void Main(string[] args)
{
Task.Factory.StartNew
(
() =>
{
// Imagine sleep is a long task which ends in 10 seconds
Thread.Sleep(10000);
// We release the whole AutoResetEvent
ResetEvent.Set();
}
);
// Once other thread sets the AutoResetEvent, the program ends
ResetEvent.WaitOne();
}
}
Run Code Online (Sandbox Code Playgroud)
while(true)的坏习惯吗?好吧,事实上,一个真正的true while循环条件可能被认为是一种不好的做法,因为它是一个难以逾越的循环:我将始终使用可能导致true或的可变条件false。
while循环或类似AutoResetEvent方法?while循环......当您需要在等待程序结束时执行代码时。
AutoResetEvent方法......当您只需要保留主线程以防止程序结束时,但是这样的主线程只需要等待直到其他线程请求程序退出即可。
| 归档时间: |
|
| 查看次数: |
9291 次 |
| 最近记录: |