CSharp examples for Thread Asynchronous:Task
Return a Result from a Task
using System;/*w ww. j a v a 2s. com*/ using System.Threading; using System.Threading.Tasks; class MainClass { static void Main(string[] args) { Task<int> task1 = Task<int>.Factory.StartNew(() => writeDays()); Task<int> task2 = Task<int>.Factory.StartNew(() => writeMonths()); Task<int> task3 = Task<int>.Factory.StartNew(() => writeCities()); Console.WriteLine("{0} days were written", task1.Result); Console.WriteLine("{0} months were written", task2.Result); Console.WriteLine("{0} cities were written", task3.Result); Console.WriteLine("Press Enter to exit"); Console.ReadLine(); } static int writeDays() { string[] daysArray = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; foreach (string day in daysArray) { Console.WriteLine("Day of the Week: {0}", day); Thread.Sleep(500); } return daysArray.Length; } static int writeMonths() { string[] monthsArray = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; foreach (string month in monthsArray) { Console.WriteLine("Month: {0}", month); Thread.Sleep(500); } return monthsArray.Length; } static int writeCities() { string[] citiesArray = { "London", "New York", "Paris", "Tokyo", "Sydney" }; foreach (string city in citiesArray) { Console.WriteLine("City: {0}", city); Thread.Sleep(500); } return citiesArray.Length; } }