[英]Pausing within a MVC controller action
A colleague of mine wrote some code that essentially pauses for 1 second before making a webservice call to check the state of a value. 我的一位同事写了一些代码,这些代码在进行Web服务调用以检查值的状态之前基本上暂停了1秒。 This code is written in a controller action of a MVC 4 application.
此代码是在MVC 4应用程序的控制器操作中编写的。 The action itself is not asynchronous.
动作本身不是异步的。
var end = DateTime.Now.AddSeconds(25);
var tLocation = genHelper.GetLocation(tid);
while (!tLocation.IsFinished && DateTime.Compare(end, DateTime.Now) > 0)
{
var t = DateTime.Now.AddSeconds(1);
while (DateTime.Compare(t, DateTime.Now) > 0) continue;
// Make the webservice call so we can update the object which we are checking the status on
tLocation = genHelper.GetLocation(tid);
}
It appears to work but for some reason I have some concerns over it's implementation. 它似乎有效,但由于某种原因,我对它的实现有一些担忧。 Is there a better way to make this delay?
是否有更好的方法来延迟?
NOTE: 注意:
I had thought the question was a good option but he did not take it up and said it wasn't required as what he did works. 我原以为这个问题是一个很好的选择,但是他并没有接受它,并说这不是他所做的工作所必需的。
How to put a task to sleep (or delay) in C# 4.0? 如何在C#4.0中让任务进入睡眠状态(或延迟)?
For MVC and your situation, this is sufficient: 对于MVC和您的情况,这就足够了:
System.Threading.Thread.Sleep( 1000 );
A fancy way to do the same thing but with more overhead: 一种奇特的方式来做同样的事情,但有更多的开销:
Task.WaitAll( Task.Delay( 1000 ) );
Update: 更新:
Quick and dirty performance test: 快速而肮脏的性能测试:
class Program
{
static void Main()
{
DateTime now = DateTime.Now;
for( int i = 0; i < 10; ++i )
{
Task.WaitAll( Task.Delay( 1000 ) );
}
// result: 10012.57xx - 10013.57xx ms
Console.WriteLine( DateTime.Now.Subtract( now ).TotalMilliseconds );
now = DateTime.Now;
for( int i = 0; i < 10; ++i )
{
Thread.Sleep( 1000 );
}
// result: *always* 10001.57xx
Console.WriteLine( DateTime.Now.Subtract( now ).TotalMilliseconds );
Console.ReadLine();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.