Reputation: 6723
I'm somewhat new to async C#, and I'm dealing with a class which has an Awaiter
but no Task
. (It's Unity 3D's WWW
class, and I'm using these extension classes to provide WWW.GetAwaiter()
.)
I want to impose a timeout for the await
, after which I'll continue the function's logic, taking a different code path because I'll know the awaiter took too long. The intuitive solution is:
Task timeout = Task.Delay(20*1000);
await Task.WhenAny(wwwTask, timeout);
bool timedOut = !wwwTask.IsCompleted;
Since WWW
is a custom class (with GetAwaiter()
) and not a task, I need to make a task for this to work. Is making a helper function the right way to get a task for that object?
private async Task<WWW> SendRequestAsync(WWW www)
{
return await www;
}
And to get the task:
Task wwwTask = SendRequestAsync(www);
Is this timeout logic sound, and is it the easiest way to work with Tasks when there is only an awaiter?
Upvotes: 0
Views: 532
Reputation: 11
To return a task with generic change your code:
private async Task<WWW> SendRequestAsync(WWW www)
{
return await www;
}
to
private async Task<WWW> SendRequestAsync(WWW www)
{
return Task.FromResult(www);
}
Upvotes: 1