In an answer to one of my other questions, I was told that use of new Task(() => { })
is not something that is a normal use case. I was advised to use Func<Task>
instead. I have tried to make that work, but I can't seem to figure it out. (Rather than drag it out in the comments, I am asking a separate question here.)
My specific scenario is that I need the Task to not start right when it is declared and to be able to wait for it later.
Here is a LinqPad example using new Task(() => { })
. NOTE: This works perfectly! (Except that it uses new Task
.)
static async void Main(string[] args)
{
// Line that I need to swap to a Func<Task> somehow.
// note that this is "cold" not started task
Task startupDone = new Task(() => { });
var runTask = DoStuff(() =>
{
//+++ This is where we want to task to "start"
startupDone.Start();
});
//+++ Here we wait for the task to possibly start and finish. Or timeout.
// Note that this times out at 1000ms even if "blocking = 10000" below.
var didStartup = startupDone.Wait(1000);
Console.WriteLine(!didStartup ? "Startup Timed Out" : "Startup Finished");
await runTask;
Console.Read();
}
public static async Task DoStuff(Action action)
{
// Swap to 1000 to simulate starting up blocking
var blocking = 1; //1000;
await Task.Delay(500 + blocking);
action();
// Do the rest of the stuff...
await Task.Delay(1000);
}
I tried swapping the second line with:
Func<Task> startupDone = new Func<Task>(async () => { });
But then the lines below the comments with +++
in them don't work right.
I swapped the startupDone.Start()
with startupDone.Invoke()
.
But startupDone.Wait
needs the task. Which is only returned in the lambda. I am not sure how to get access to the task outside the lambda so I can Wait
for it.
How can use a Func<Task>
and start it in one part of my code and do a Wait
for it in another part of my code? (Like I can with new Task(() => { })
).