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

后端 未结 2 636
野性不改
野性不改 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: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
                                }
                            });     
        }
    }
    

提交回复
热议问题