0

I have the following code:

DateTime start = DateTime.Now;
Func<Task<double>> f = async () =>
{
    await Task.Delay(3000, cts.Token);
    return (DateTime.Now - start).TotalMilliseconds;
};
Task<double> delayTask = f();

But I can't figure it out how to write it as a single statement without assigning the delegate to a variable first. That is, I feel like I should be able to just do something like

Task<double> delayTask = (async () =>
{
    await Task.Delay(3000, cts.Token);
    return (DateTime.Now - start).TotalMilliseconds;
})();

or even

Task<double> delayTask = new Task<double>(async () =>
{
    await Task.Delay(3000, cts.Token);
    return (DateTime.Now - start).TotalMilliseconds;
});

but both give compilation errors. What am I missing?

i3arnon
  • 113,022
  • 33
  • 324
  • 344
Dylan Nicholson
  • 1,235
  • 14
  • 20

2 Answers2

4

I think what you're looking for is:

Task<double> delayTask = new Func<Task<double>>(async () => 
{  
    await Task.Delay(3000, cts.Token); 
    return (DateTime.Now - start).TotalMilliseconds; 
})();
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92
  • Yep, that just came to me a few minutes ago, tried it out and sure enough it does the job, though it still seem like more syntax that should be needed. – Dylan Nicholson Nov 19 '14 at 09:55
0

You're getting errors for the same reason you can't compile this:

var f = async () =>
{
    await Task.Delay(3000, cts.Token);
    return (DateTime.Now - start).TotalMilliseconds;
};

You must specify the required type somewhere for type inference to be able to work. More here.

You can however remove the need for a variable with a simple cast:

var delayTask = ((Func<Task<double>>) (async () =>
{
    await Task.Delay(3000, cts.Token);
    return (DateTime.Now - start).TotalMilliseconds;
}))();
Community
  • 1
  • 1
i3arnon
  • 113,022
  • 33
  • 324
  • 344