|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using System.Threading; |
| 6 | +using System.Threading.Tasks; |
| 7 | + |
| 8 | +namespace LU3 |
| 9 | +{ |
| 10 | + class Program |
| 11 | + { |
| 12 | + static void Main(string[] args) |
| 13 | + { |
| 14 | + /*// use an Action delegate and named method |
| 15 | + Task task1 = new Task(new Action(printMessage)); |
| 16 | + // use an anonymous delegate |
| 17 | + Task task2 = new Task(delegate { printMessage() }); |
| 18 | + // use a lambda expression and a named method |
| 19 | + Task task3 = new Task(() => printMessage()); |
| 20 | + // use a lambda expression and an anonymous method |
| 21 | + Task task4 = new Task(() => { printMessage() }); |
| 22 | +
|
| 23 | + // Launch the tasks |
| 24 | + t1.Start(); |
| 25 | + t2.Start(); |
| 26 | + t3.Start(); |
| 27 | + t4.Start(); |
| 28 | +
|
| 29 | + // Construct a started task |
| 30 | + Task t2 = Task.Factory.StartNew(() => printMessage()); |
| 31 | +
|
| 32 | + // Construct a started task using Task.Run. |
| 33 | + Task t3 = Task.Run(() => printMessage()); |
| 34 | + * */ |
| 35 | + |
| 36 | + TaskParallelismSimpleExample(); |
| 37 | + |
| 38 | + Console.WriteLine(); |
| 39 | + } |
| 40 | + |
| 41 | + private static void TaskParallelismSimpleExample() |
| 42 | + { |
| 43 | + //Construct a started task |
| 44 | + Task t1 = Task.Factory.StartNew( |
| 45 | + () => |
| 46 | + { |
| 47 | + Console.WriteLine("Task ParalellismSimpleExample, Task = {0}, Thread = {1}", Task.CurrentId |
| 48 | + , Thread.CurrentThread.ManagedThreadId); |
| 49 | + }); |
| 50 | + |
| 51 | + Console.WriteLine("t1 has been launched. Task = {0}, Thread = {1}", Task.CurrentId |
| 52 | + , Thread.CurrentThread.ManagedThreadId); |
| 53 | + //Wait for the task to finish |
| 54 | + t1.Wait(); |
| 55 | + |
| 56 | + //Construct a started task using Task.Run |
| 57 | + Task t2 = Task.Run( |
| 58 | + () => |
| 59 | + { |
| 60 | + Console.WriteLine("t2 has been launched. Task = {0}, Thread = {1}", Task.CurrentId |
| 61 | + , Thread.CurrentThread.ManagedThreadId); |
| 62 | + }); |
| 63 | + //Wait for the task to finish |
| 64 | + t2.Wait(); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments