4

I have been having a bit of a play with TPL and it's associated Tasks.

Question 1 : I need some feedback on whether I am going down the right path in terms of how I am trying to incorporate Tasks into a class.

The class has a Start and Stop method.

In the implementation of Start I want to create a fire-and-forget Task to do the processing. The code calling the Start method of the instance should then be free to call Stop as required (eg the calling code is a windows service so in the OnStop event I might want to call Stop on any instances ie "I want to shutdown now so everyone stop what you are doing!").

I have seen plenty of code similiar to the following

Task myTask = Task.Factory.StartNew(GoOffAndDoSomething, [associated cancellation token]);

try{
    myTask.Wait();
}catch (AggregateException ae){
    //Process aggregate exceptions as required
}

...but I don't want to Wait because this is blocking my calling thread and I can't call Stop method (or do anything else) etc.

So I think I have to do something like this....

Task myTask = Task.Factory.StartNew(GoOffAndDoSomething, [associated cancellation token]);

//Use non-blocking ContinueWith  
myTask.ContinueWith(HandleBadStuffThatHappened, TaskContinuationOptions.NotOnRanToCompletion);

//The method to handle exceptions etc
Action<Task> HandleBadStuffThatHappened = (antecendent) =>
{
    // "Observe" your antecedent's exception so as to avoid an exception
    // being thrown on the finalizer thread
    var badStuffHappened = antecendent.Exception;

    //Handle\rethrow exception etc     
};

Question 2 : Is this the type of approach I need to take?

I know some might suggest creating the Start method as a Task outside this class and handling cancellation\exceptions in the calling code but there might be many instances of the class created in the windows service so I just want the Task creation, and handling of any exceptions, to be done in the class itself.

EDIT : Close to answering my own question here but I will leave it open to comments for a while longer in case this extra information make my intent clearer and provide an opportunity for others to add

So...I think I was heading down the right path. As stated in one of my comments I have done a small app to play around with approach based on further research I have done. The relevant methods from my class are shown here. This and it's comments should show you my current proposed approach. I think I am basically there.

    //Called by external client to get things rolling
    public void Start()
    {
        //Could use Status property of Task but it is simpler to just use a class property than deal  
        //with all the different stages a Task can be in.
        if (!IsRunning) 
            {
            IsRunning = true; //set it first in case there are any delays\issues with starting up
            _tokenSource = new CancellationTokenSource();
            _processing = Task.Factory.StartNew(process, _tokenSource.Token);
            //Use the OnlyOnFaulted task continuation option. This is different to 
            //my .NotOnRanToCompletion suggestion previously
            _processing.ContinueWith(antecedent => HandleException(antecedent.Exception), 
            TaskContinuationOptions.OnlyOnFaulted);

            //There's no 'Task.Wait' here, I just want to fire and forget this Task.
        }
    }

    //Look at the call to ContinueWith in Start method. This is what I want to do if the Task goes to
    //a Faulted state, ie an exception occurred.
    private void HandleException(AggregateException ae)
    {
        IsRunning = false;

        //Log or handle errors errors as required.
        //ae.Flatten().InnerException will give the exception that caused the failure.

        //Finally Dispose Task here. Typically I retry code a specified number of times 
        //(retry code not shown) before finally throwing the exception, and typically I don't do any 
        //explicit handling other than to Log\Alert the issue. So at this poin the Task is 'beyond saving'
        //so get rid of it.
        _processing.Dispose();
    }

    //Stop method which can be called by external client.
    public void Stop()
    {
        //Use the cancellation token created in Start() to cancel the Task
        _tokenSource.Cancel();
        IsRunning = false; //set flag last in case something occurs during cancellation process
    }

    //What I wired up my Task to do
    private void process()
    {
        while (!_tokenSource.IsCancellationRequested)
        {
           //So assuming normal UN-exceptional operation of your code then just
           //do stuff here until Stop method called by client
        }
    }

A note on throwing exceptions to client

At one point I did investigate throwing exception to client (I know this is not inline with original question but I was curious) and handle\log there. One way (there were several others I saw) to do this is when an Exception occurs have this class raise an event with the Exception as a parameter. The client needs to ensure it subscribes to this event to be notified of exceptions.

I do not require this functionality, and it complicated things, instead I am just doing all Handling\Logging of exception in the class itself.

Good TPL Options document

Have a look at http://download.microsoft.com/download/B/C/F/BCFD4868-1354-45E3-B71B-B851CD78733D/TPLOptionsTour.pdf it looks at al the different 'Options' you have when running tasks and is where I got the idea to use the 'OnlyOnFaulted' approach which is a typical use for exception handling (see page 19).

Any further comment welcomed.

2 Answers 2

1

The second approach clearly is better as it does not require the Start method to wait until the "fire-and-forget" initialization is done.

Be careful though if somebody calls stop while the start code is still running. This might be a race condition. You probably need to synchronize here.

You could also keep track of all running tasks in a synchronized HashSet<Task> and WaitAll on them in your stop method. That would make sure that no code still runs after Stop has completed.

2
  • Some good points there. The cancellation token associated with the start of the Task would be used to cancel the task in the Stop method, with the executing code checking to see if a request to cancel has been made so I think that would avoid issues. I don't plan to have more than one Task running in the class, but that might change of course. I will keep race conditions in mind if I am updating common data. I would be interested in what others have to say. Aug 12, 2012 at 23:31
  • At this point I am going to do a smaller test app and see how things work. Might also have to consider how to handle the AggregateExceptions generated by exceptions in Tasks. Aug 12, 2012 at 23:40
0

I am going with my own answers to my question. Other posts, while helpful, did not contribute significantly to me coming up with a solution

Not the answer you're looking for? Browse other questions tagged or ask your own question.