Sometimes (Visual Studio) error messages are just misleading

Take into account this code

Task.Factory.StartNew(
    () =>
    {
        throw new Exception();
    }).
    ContinueWith(
        t =>
        {
        },
    TaskScheduler.FromCurrentSynchronizationContext);

Which results in following error:

error CS1593: Delegate 'System.Action<System.Threading.Tasks.Task,object>' does not take 1 arguments

If I use an overload that takes TaskContinuationOptions.OnlyOnFaulted instead of TaskScheduler.FromCurrentSynchronizationContext it just works. There are two overloads (among twenty of them) of ContinueWith:

public Task ContinueWith(Action<Task> continuationAction, TaskContinuationOptions continuationOptions);
public Task ContinueWith(Action<Task> continuationAction, TaskScheduler scheduler);

So, why does the later work and the former doesn’t? Can you guess without reading on?

The explanation is really simple - TaskScheduler.FromCurrentSynchronizationContext is not a property but a method and thus it should be used like TaskScheduler.FromCurrentSynchronizationContext(). Once brackets are in place it works. Rookie mistake.

However the C# compiler’s error message is misleading in this case. Instead of reporting that FromCurrentSynchronizationContext is a method and not a property it yields “can’t find proper overloaded method”. At least it could yield both errors.


Avtor: Anonymous, objavljeno na portalu SloDug.si (Arhiv)

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.