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:
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.
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.