How to construct a Task without starting it?
var t = new Task<int>(() => GetIntAsync("3").Result);
Or
var t = new Task<int>((ob) => GetIntAsync((string) ob).Result, "3");
To avoid using lambda, you need to write a static method like this:
private static int GetInt(object state)
{
return GetIntAsync(((string) state)).Result;
}
And then:
var t = new Task<int>(GetInt, "3");
To use the Task
constructor that accepts an object state
argument you must have a function that accepts an object
argument too. Generally this is not convenient. The reason that this constructor exists is for avoiding the allocation of an object (a closure) in hot paths. For normal usage the overhead of closures is negligible, and avoiding them will complicate your code for no reason. So this is the constructor you should use instead:
public Task (Func<TResult> function);
...with this lambda as argument:
() => GetIntAsync("3")
There is one peculiarity in your case though: the lambda you pass to the constructor returns a Task<int>
. This means that the generic type TResult
is resolved to Task<int>
, and so you end up with a nested task:
var t = new Task<Task<int>>(() => GetIntAsync("3"));
Starting the outer task will result to the creation of the inner task. To get the final result you'll have to use the await
operator twice, one for the completion of the outer task, and one for the completion of the inner task:
static async Task Main(string[] args)
{
var outerTask = new Task<Task<int>>(() => GetIntAsync("3"));
//...
outerTask.Start(); // or outerTask.RunSynchronously() to use the current thread
//...
Task<int> innerTask = await outerTask; // At this point the inner task has been created
int result = await innerTask; // At this point the inner task has been completed
}
Had a similar issue where we wanted to ensure a task was re-usable without re-starting the task. Rx saved our bacon. You'll need the nuget package System.Reactive
.
See below GetIntTask
returns a Task that isn't started, and GetIntOnce
ensures the task gets started, and the result of the task is buffered and replayed to any callers (with Replay(1)
)
async Task Main()
{
var awaitableResult = GetIntOnce();
Console.WriteLine("Has the task started yet? No!");
var firstResult = await awaitableResult;
Console.WriteLine($"Awaited Once: {firstResult}");
var secondResult = await awaitableResult;
Console.WriteLine($"Awaited Twice: {secondResult}");
}
public static IObservable<int> GetIntOnce()
{
return Observable.FromAsync(() =>
{
var t = GetIntTask();
t.Start();
return t;
}).Replay(1).AutoConnect();
}
public static Task<int> GetIntTask()
{
var t = new Task<int>(
() =>
{
Console.WriteLine("Task is running!");
return 10;
});
return t;
}
The output is:
Has the task started yet? No!
Task is running!
Awaited Once: 10
Awaited Twice: 10