Create And Start A Task
internal static class Program
{
public static void Print(char c)
{
int i = 500;
while (i-- > 0)
{
System.Console.WriteLine(c);
}
}
public static void Main()
{
//doing two thing at same time
//1. making the task
//2. starting it
Task.Factory.StartNew(() => Print('A'));
//or
//-- you ought to start the task in this case
var t = new Task(() => Print('G'));
t.Start();
//below runs in main thread
Print('M');
System.Console.WriteLine("---end---");
}
}
Overload method
internal static class Program
{
public static void PrintOverLoaded(object s)
{
int i = 500;
while (i-- > 0)
{
System.Console.WriteLine(s);
}
}
public static void Main()
{
//overloaded method
//public Task StartNew(Action
Generic Task
internal static class Program
{
public static string? ToUpperCase(object obj)
{
System.Console.WriteLine($"Task id is {Task.CurrentId}");
return obj.ToString().ToUpper();
}
public static void Main()
{
string name1 = "anurag";
string name2 = "nayak";
var task1 = new Task(ToUpperCase, name1);
task1.Start();
var task2 = Task.Factory.StartNew(ToUpperCase, name2);
System.Console.WriteLine($"converting to upper case {task1.Result}");
System.Console.WriteLine($"converting to upper case {task2.Result}");
System.Console.WriteLine("---Ending generic task method!!---");
}
}
Output
Task id is 1
Task id is 2
converting to upper case ANURAG
converting to upper case NAYAK
---Ending generic task method!!---
anuragnayak@192 helloworld %