Summary: Full use of task async features
Code implementation:
1. Implementation of Task timeout exit task
2. Perform multiple tasks together
<summary>
It takes ms seconds to get things done.
</summary>
<param name= "Time" ></param>
<returns></returns>
Static async task<string> Doing (int time, string name = "I")
{
Console.WriteLine (name+ "came");
Await Task.delay (Timespan.frommilliseconds (time));
return string. Format ("This live {1} dried: {0}ms", time,name);
}
<summary>
Set Timeout task if time-out returns
</summary>
<param name= "Needtimeout" ></param>
<returns></returns>
Static async task<string> TimeOut (bool needtimeout)
{
Console.WriteLine (Needtimeout);
var t=new Stopwatch ();
T.start ();
var timeouttask = Task.delay (150);//1. Set a task that is timed out
var doing = doing (needtimeout 100:300);//2. Tasks that really need to be performed
var task = await task.whenany (doing,timeouttask);//return any one of the completed tasks
if (task = = timeouttask)//If the timeout task is completed first, it is a pity that he did not finish!
{
Return "It's a pity he didn't finish!" ";
}
T.stop ();
Console.WriteLine ("Time-consuming:" +t.elapsed.totalmilliseconds);
return await doing;
}
<summary>
Multiple tasks to execute together
</summary>
<returns></returns>
Static async Task Tasks ()
{
var t = new Stopwatch ();
T.start ();
var list=new list<string> ();
var T1 = Doing (1000, "1000");//1. Defining Tasks
var t2 = Doing (1500, "1500");
var t3 = Doing (1200, "1200");
var tasks = new[] {t1, T2, T3};//2. Task Group
var process = tasks. Select (Async TT =>//3. Wait for the task to end and save the value
{
var result = await TT;
List. ADD (result);
});
Await Task.whenall (process);//4. Wait for the processing to complete
foreach (var i in list)//5. viewing results
{
Console.WriteLine (i);
}
T.stop ();
Console.WriteLine ("Time Consuming:" + t.elapsed.totalmilliseconds);
}
C # uses task to implement tasks that time out and multitask to execute together