Question

So I found that annoyingly, with custom task methods, I need to always return a new Task, like in Foo0() below. But interestingly in Xamarin, you can drop the return new Task block if you put an async keyword.

Are Foo0 and Foo1 equivalent?

Is this a glitch of Xamarin implementation, or does this work in VS2012 as well?

But Foo1 gives a compiler warning, and I can't just remove the async keyword, or it will stop compiling even though the body of the code remains the same. (I find the extra new Task block in Foo0 redundant, it should be obvious from the method declaration that I want to run a new task.)

// the following is explicit with returning a new task
Task<int> Foo0()
{
    return Task.Run(() =>
    {
        return 5;
    });
}

// the following gives warning "Async block lacks `await` operator and will run synchronously"
async Task<int> Foo1()
{
    return 5;
}

/* the following does not compile
Task<int> Foo2()
{
    return 5;
}
*/
Was it helpful?

Solution

Is this a glitch of Xamarin implementation, or does this work in VS2012 as well?

This is how async works in C# (both VS2012 and Xamarin).

it should be obvious from the method declaration that I want to run a new task

Not at all. A task is nothing more than a "future"; it represents an asynchronous operation. One possible way to do this is by queueing work to the thread pool (such as Task.Run), but that is a rare approach in the asynchronous world.

In particular, async does not queue work to the thread pool. It is not using Task.Run or anything like it underneath. As the compiler warning states, it will run synchronously (on the current thread) and then return an already-completed task. This is almost certainly what you don't want, hence the warning.

So, Foo0 and Foo1 are completely different. Foo0 queues work to the thread pool and returns a task representing that work. Foo1 does the work immediately and then returns an already-completed task.

I have an async intro on my blog if you want more information about async and await.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top