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.

Leave a Reply