How to determine whether Task.Run is completed within a loop

后端 未结 2 683
野性不改
野性不改 2021-02-14 17:05

This may be an odd question and it is really for my educational purpose so I can apply it in future scenarios that may come up.

I am using C#.

I am stress testin

2条回答
  •  没有蜡笔的小新
    2021-02-14 17:42

    IMO you do not need the timer. Using Task Continuation you subscribe to the done event:

    System.Threading.Tasks.Task
    .Run(() => 
    {
        // simulate processing
        for (var i = 0; i < 10; i++)
        {
            Console.WriteLine("do something {0}", i + 1);
        }
    })
    .ContinueWith(t => Console.WriteLine("done."));
    

    The output is:

    do something 1
    do something 2
    .
    .
    do something 9
    do something 10
    done
    

    Your code could look like this:

    var webTask = Task.Run(() =>
    {
        try 
        { 
            wcf.UploadMotionDynamicRaw(bytes);  //my web service
        }
        catch (Exception ex)
        {
            //deal with error
        }
    }).ContinueWith(t => taskCounter++);
    

    With task continuation you could even differentiate between failed and success process result, if you want to count only successfull tasks - using the TaskContinuationOptrions.

提交回复
热议问题