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

后端 未结 2 637
野性不改
野性不改 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.

    0 讨论(0)
  • 2021-02-14 17:51

    You can wait for your task to complete by awaiting your task like this

    await webTask;
    

    that will asynchronously wait for 'webTask' to complete. Instead of the timer you can use await Task.Delay which will asynchronously wait for the delay to expire. I would also consider making the wcf call asynchronous so you don't have to call inside Task.Run. See this question for some tips.

    I'd rewrite the code as follows:

    public async Task UploadAsync()
    {
        while(true)
        {
            await Task.Delay(1000); // this is essentially your timer
    
            // wait for the webTask to complete asynchrnously
            await webTask;
    
            //keep count of competed tasks
    
            webTask = Task.Run(() =>
                            {
                                try 
                                { 
                                    // consider generating an asynchronous method for this if possible.
                                    wcf.UploadMotionDynamicRaw(bytes);  //my web service
                                }
                                catch (Exception ex)
                                {
                                    //deal with error
                                }
                            });     
        }
    }
    
    0 讨论(0)
提交回复
热议问题