private static void Simple_TaskCreationOptions() { var t = Task.Factory.StartNew((object obj) => { SomeCustomData data = obj as SomeCustomData; if (data != null) { for (int i = 0; i < data.Count; ++i) { for (int j = 0; j < data.Count; ++j) { Console.WriteLine($"Mul - {i} x {j} = {i * j}"); data.LastResult = i * j; } } } }, new SomeCustomData() { Count = 100 }, // Specifies flags that control optional behavior for the creation and execution of tasks. TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness); for (int i = 0; i < 100; ++i) { SomeCustomData data = t.AsyncState as SomeCustomData; Console.WriteLine($"Task status: {t.Status}, ID: {t.Id} last state: {data.LastResult}"); Thread.Sleep(10); } }
// Creating and starting task in one operation // Can specify task creation options and cancellation token // AsyncState - can get access to task data which was pased. private static void Simple_TaskFactory() { var t = Task.Factory.StartNew((object obj) => { SomeCustomData data = obj as SomeCustomData; if (data != null) { for (int i = 0; i < data.Count; ++i) { for (int j = 0; j < data.Count; ++j) { Console.WriteLine($"Mul - {i} x {j} = {i * j}"); data.LastResult = i * j; } } } }, new SomeCustomData() { Count = 100 }); for (int i = 0; i < 100; ++i) { SomeCustomData data = t.AsyncState as SomeCustomData; Console.WriteLine($"Task status: {t.Status}, ID: {t.Id} last state: {data.LastResult}"); Thread.Sleep(10); } t.Wait(); Console.WriteLine($"Task status: {t.Status}"); Console.WriteLine($"Task IsCompletedSuccessfully: {t.IsCompletedSuccessfully}"); }
private static void Multiplication(object obj) { SomeCustomData data = obj as SomeCustomData; if (data != null) { for (int i = 0; i < data.Count; ++i) { for (int j = 0; j < data.Count; ++j) { Console.WriteLine($"Mul - {i} x {j} = {i * j}"); data.LastResult = i * j; Thread.Sleep(50); } } } }