Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. This code is written in a controller action of a MVC 4 application. 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:

  1. We are not using .NET 4.5 and will not change to this in this solution
  2. Javascript scrip options like SignalR are not an option at present

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?

like image 363
dreza Avatar asked Jan 29 '14 01:01

dreza


1 Answers

For MVC and your situation, this is sufficient:

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();
    }
}
like image 92
Moho Avatar answered Oct 11 '22 22:10

Moho