Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

await array; by implementing extension method for array

Tags:

c#

async-await

I wanted to make an array awaitable by implementing an extension method

public static IAwaitable GetAwaiter(this mytype[] t)
{
    return t.First().GetAwaiter();
}

but even though IntelliSense says "(awaitable) mytype[]", the compiler gives me an error when using

mytype[] t = new mytype[] { new mytype(), new mytype() };
await t;

Calling await on a single object of mytype works fine. Why is that? Am I doing something wrong? Thanks for your help.

like image 404
David Avatar asked Oct 21 '22 20:10

David


1 Answers

I think this is a bug in the compiler and you should report it.

I can verify that this code doesn't work (using Task and TaskAwaiter, not custom types):

public static TaskAwaiter GetAwaiter(this Task[] tasks)
{
    return tasks.First().GetAwaiter();
}

Task[] tasks = …;
await tasks;

(It produces the error "Cannot await 'System.Threading.Tasks.Task[]'", as reported.)

But swapping array for IEnumerable (in both the the method and the local) does work:

public static TaskAwaiter GetAwaiter(this IEnumerable<Task> tasks)
{
    return tasks.First().GetAwaiter();
}

IEnumerable<Task> tasks = …;
await tasks;

Interestingly, with the fixed version, awaiting an array directly still doesn't work. But for example awaiting IList does work.

like image 113
svick Avatar answered Oct 26 '22 22:10

svick