Click here to Skip to main content
15,888,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an that calls a method Foo, which takes a long time. Is there a way to call Foo *asynchronously* so that the rest of the code doesn't have to wait for Foo to finish to carry on?

I am trying:
Task.Run(() => Foo("bar"));


Are there any pros or cons of doing it using Tasks like above? Or is there a better way?

What I have tried:

Task.Run(() => Foo("bar"));
Posted
Updated 15-May-22 10:00am
v3

1 solution

That is what Task.Run does: Task.Run Method (System.Threading.Tasks) | Microsoft Docs[^]
For example:
C#
using System;
using System.Threading.Tasks;
using System.Threading;
					
public class Program
{
	public static void Main()
	{
		Console.WriteLine("Hello World");
		Task.Run(() => Foo("bar"));
		Console.WriteLine("After");
		Thread.Sleep(500);
		Console.WriteLine("Done");
	}
	static void Foo(string s)
	{
		Thread.Sleep(200);
		Console.WriteLine(s);
	}
}
Will give you:
Hello World
After
bar
Done
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900