Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Task exception handling fail fast?

Tags:

c#

I provide a method based on the TPL like:

    private Task AddItemAsync(Uri url, CancellationToken token)
    {
        if (url == null)
            throw new ArgumentNullException("url");

        var result = Task.Factory.StartNew(() => 
        {
            // Do some stuff here
        }, token);
        return result;
    }

Now I am wondering if it is OK to throw the exception at once or to throw it within the task.StartNew {} stuff.

like image 509
Franz Gsell Avatar asked Mar 20 '23 23:03

Franz Gsell


1 Answers

Throwing it immediately is almost certainly the right approach. I'm sure somebody can think of some obscure reason not to--but based on your question it sounds like url is 100% required. In other words, if it wasn't always required then that may be a good reason not to throw it there.

But even then, I'd try and find a way to know I'm going to need it.

Throwing that exception on the background thread is going to be a hard row to hoe.

like image 166
Mike Perrenoud Avatar answered Mar 23 '23 13:03

Mike Perrenoud