How to determine if Task.Run has completed in a loop

This may be a strange question, and it really is for my educational purpose, so I can apply it in future scenarios that may arise.

I am using C #.

I am stressed, so this is not exactly production code.

I upload data to my server through a web service.

I start the service using Run.Task.

I check if the task is completed before allowing the next Run.Task to run.

This is done in a loop.

However, since I am using a modular declared task, will the result not be affected? I could declare a local variable Task.Run, but I want to see how far I can get this question. 1.

If Task.Run can raise an event to say that it has completed, may this not be a problem?

This is my code:

// module declaration:

private static Task webTask = Task.Run(() => { System.Windows.Forms.Application.DoEvents(); });

// ,

if (webTask.IsCompleted)
{
   //keep count of competed tasks
}


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

IMO . , :

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."));

:

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

:

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

, - TaskContinuationOptrions.

+6

, ,

await webTask;

'webTask'. await Task.Delay, . wcf, Task.Run. . .

:

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
                            }
                        });     
    }
}
+2

Source: https://habr.com/ru/post/1569865/


All Articles