在MVC控制器操作中暂停

时间:2014-01-29 01:32:33

标签: c# asp.net-mvc-4

我的一位同事在进行网络服务调用以检查值的状态之前写了一些基本上暂停1秒的代码。此代码是在MVC 4应用程序的控制器操作中编写的。动作本身不是异步的。

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);
}

它似乎有效,但由于某种原因,我对它的实施有一些担忧。有没有更好的方法来实现这种延迟?

注:

  1. 我们不使用.NET 4.5,并且在此解决方案中不会更改
  2. 目前无法选择像SignalR这样的Javascript脚本选项
  3. 我原本以为这个问题是一个不错的选择,但是他没有接受,并说这不是他所做的工作所必需的。

    How to put a task to sleep (or delay) in C# 4.0?

1 个答案:

答案 0 :(得分:36)

对于MVC和你的情况,这就足够了:

System.Threading.Thread.Sleep( 1000 );

一种花哨的方式来做同样的事情,但有更多的开销:

Task.WaitAll( Task.Delay( 1000 ) );

更新

快速而肮脏的性能测试:

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();
    }
}