Task.Delay有问题或者我做错了什么?

时间:2013-06-21 13:17:08

标签: c# asp.net-mvc-4 .net-4.5 async-await

  编辑:我做错了什么。问题是使用datetime对象执行计时代码并输出毫秒而不是totalmiliseconds。

简而言之,我在.net 4.5上运行了一个新的mvc4项目,并在homecontroller中使用以下代码。

    public async Task<ActionResult> Index()
    {
        Int32[] Delays = new Int32[] { 1999, 500, 20 }; 
        List<String> result = new List<String>();

        var now = DateTime.Now;

        result.Add(String.Format("Started at: {0}", now.ToString("MM/dd/yyyy hh:mm:ss.fff tt")));

        //TAKE 1
        result.Add("Take 1");
        await Task.WhenAll(Delays.Select(async x => result.Add(await Slow(x, now, Array.IndexOf(Delays, x), "take 1"))));

        //TAKE 2
        result.Add("Take 2");
        var tasks = Delays.Select((x, i) => Slow(x, now, i, "take 2")).ToList();
        await Task.WhenAll(tasks);
        result.AddRange(tasks.Select(x => x.Result));

        return View(result);
    }

My Slow方法看起来像这样......

    private async Task<String> Slow(Int32 ms, DateTime dt, int i, String take)
    {
        Response.Write(String.Format("[{3}][index:{0}][delay:{2}] pre sleep - {1} <br />", i, DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), ms, take));

        await Task.Delay(ms);

        Response.Write(String.Format("[{3}][index:{0}][delay:{2}] after sleep - {1} <br />", i, DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), ms, take));

        var delayedtime = DateTime.Now;

        var diff = delayedtime - dt;

        return String.Format("Slept for : [{2}]{0} miliseconds. diff was : {1}", ms, diff.Milliseconds, take);
    }

输出看起来像这样......

[take 1][index:0][delay:1999] pre sleep - 06/21/2013 02:46:25.338 PM
[take 1][index:1][delay:500] pre sleep - 06/21/2013 02:46:25.340 PM
[take 1][index:2][delay:20] pre sleep - 06/21/2013 02:46:25.340 PM
[take 1][index:2][delay:20] after sleep - 06/21/2013 02:46:25.368 PM
[take 1][index:1][delay:500] after sleep - 06/21/2013 02:46:25.849 PM
[take 1][index:0][delay:1999] after sleep - 06/21/2013 02:46:27.347 PM
[take 2][index:0][delay:1999] pre sleep - 06/21/2013 02:46:27.347 PM
[take 2][index:1][delay:500] pre sleep - 06/21/2013 02:46:27.347 PM
[take 2][index:2][delay:20] pre sleep - 06/21/2013 02:46:27.347 PM
[take 2][index:2][delay:20] after sleep - 06/21/2013 02:46:27.382 PM
[take 2][index:1][delay:500] after sleep - 06/21/2013 02:46:27.861 PM
[take 2][index:0][delay:1999] after sleep - 06/21/2013 02:46:29.359 PM

Started at: 06/21/2013 02:46:25.336 PM
Take 1
Slept for : [take 1]20 miliseconds. diff was : 32
Slept for : [take 1]500 miliseconds. diff was : 513
Slept for : [take 1]1999 miliseconds. diff was : 11
Take 2
Slept for : [take 2]1999 miliseconds. diff was : 23
Slept for : [take 2]500 miliseconds. diff was : 525
Slept for : [take 2]20 miliseconds. diff was : 46 

我很惊讶的是,1999毫秒的延迟报告它在5毫秒之后完成,而其他两个延迟似乎工作得很好。 一旦延迟参数高于'999'毫秒,我就会得到这种行为。

我的问题是,如果我做错了什么,如果延迟响应了我不知道的配置或者方法是否被窃听。

1 个答案:

答案 0 :(得分:2)

diff.Milliseconds测量TimeSpan的ms部分。也许你的意思是:

diff.TotalMilliseconds