Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

task

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 testing so this is not quite production code.

I upload data to my server via a web service.

I start the service off using a Run.Task.

I check to see if the Task is completed before allowing the next Run.Task to begin.

This is done within a loop.

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

If the Task.Run can raise an event to say it is completed then this may not be an issue?

This is my code:

//module declaration:

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

//in a function called via a timer

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


webTask = Task.Run(() =>
{
    try 
    { 
         wcf.UploadMotionDynamicRaw(bytes);  //my web service
    }
    catch (Exception ex)
    {
        //deal with error
    }
);
like image 443
Andrew Simpson Avatar asked Jan 04 '15 10:01

Andrew Simpson


People also ask

Does Task run use a new thread?

NET code does not mean there are separate new threads involved. Generally when using Task. Run() or similar constructs, a task runs on a separate thread (mostly a managed thread-pool one), managed by the . NET CLR.

Is Task run asynchronous?

In . NET, Task. Run is used to asynchronously execute CPU-bound code.


1 Answers

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.

like image 99
keenthinker Avatar answered Oct 16 '22 23:10

keenthinker