I have two async methods, Test1 and Test2.
In Test1, I want to call Test2 "in a new thread".
In other words, I want a separate "thread" to go to execute Test2, and Test1 step over Test2 call and do not wait for it to finish.
private async Task Test2()
{
// some time-consuming work to do...
}
public async Task Test1()
{
// How to call Test2 and immediately move on to the next line and let a separate "thread" to
// execute Test2?
}
CodePudding user response:
Let's assume that Test2
has some CPU-intensive logic and some asynchronous calls:
private async Task Test2()
{
for (var i = 1; i < 1_000_000; i )
{
}
await Task.Delay(TimeSpan.FromMinutes(1));
for (var i = 1; i < 1_000_000; i )
{
}
}
If Test2
is invoked without await
, then current thread would execute logic before fist await
in Test2
method prior to returning to Test1
. Meaning execution will return to Test1
only after the first for
loop finishes:
public async Task Test1()
{
var _ = Test2();
}
If you require Test1
to continue execution immediately after the Test2
invocation, than it has to be scheduled to another thread from ThreadPool
, which can be done with Task.Run
, for example:
public async Task Test1()
{
var _ = Task.Run(() => Test2());
}
In this case you don't have the control when Test2
actually gets executed by ThreadPool
(it can happen that Test1
exits even before Test2
is started) and the task, returned by Task.Run
will complete only when Task2
exits or throws an error. So you can await
it or use the task later in your code, or simply ignore it, if your logic is not concerned about the result.
And if you are not going to await the task from Test2
method, it's worthwhile to catch and handle/log possible errors in it directly, otherwise it will fail silently, which might cause hard to investigate issues.