我有时会遇到以下形式的代码:
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)
我假设有更好的方法来阻止服务(或天蓝色工作者角色)退出.有人对我有建议吗?
我在各种网站上看到Thread.Abort不是很好用.在这种情况下,如何实现超时模式?例如,我已经读过MS在整个框架中使用下面的模式(我已经用扩展方法包装).就个人而言,我认为这是一个非常酷的扩展,但我担心Thread.Abort.有没有人有更好的方法?
public static bool CallandWait(this Action action, int timeout)
{
Thread subThread = null;
Action wrappedAction = () =>
{
subThread = Thread.CurrentThread;
action();
};
IAsyncResult result = wrappedAction.BeginInvoke(null, null);
if (((timeout != -1) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted))
{
if (subThread != null)
{
subThread.Abort();
}
return false;
}
else
{
wrappedAction.EndInvoke(result);
return true;
}
}
Run Code Online (Sandbox Code Playgroud)