SoFunction
Updated on 2025-03-01

C# uses Task to implement task timeout and multi-task execution together

Preface

In fact, Task has similar functions to thread pool ThreadPool, but it is simpler and more intuitive to write. The code is more concise, use Task to operate. It can easily control the execution method like a thread.

There are two ways to create a Task, one is to use a constructor, and the other is to use a Task.

As shown in the following code

1. Create Task using constructor

Task t1 = new Task(MyMethod);

2. Create Task using

Task t1 = (MyMethod);

In fact, these two methods are the same, which are the management of Task and scheduling management. Those who are interested in learning can conduct in-depth research. This is not the scope of this article. Friends who need it can go in and study.

This article will make full use of Task's asynchronous function, let's take a look at the detailed introduction below.

Code implementation:

1. The task timeout has been achieved and the task is exited

2. Multiple tasks are executed together

  /// <summary>
  /// It takes ms seconds to complete it  /// </summary>
  /// <param name="time"></param>
  /// <returns></returns>
  static async Task<string> Doing(int time, string name = "I")
  {
   (name+"Come");
   await ((time));
   return ("This life{1}Did it:{0}ms ", time,name);
  }
  /// <summary>
  /// Set the timeout task if the timeout returns  /// </summary>
  /// <param name="needTimeOut"></param>
  /// <returns></returns>
  static async Task<string> TimeOut(bool needTimeOut)
  {
   (needTimeOut);
   var t=new Stopwatch();
   ();
   var timeOutTask = (150);//1. Set a timeout task   var doing = Doing(needTimeOut ? 100 : 300);//2. Real tasks to be executed   var task = await (doing,timeOutTask);//Return any completed task   if (task == timeOutTask)//If the timeout task is completed first, then return. It’s a pity that he did not complete it!   {
    return "It's a pity that he didn't finish!";
   }
   ();
   ("time consuming:"+);
   return await doing;
  }
  /// <summary>
  /// Multitasking together  /// </summary>
  /// <returns></returns>
  static async Task Tasks()
  {
   var t = new Stopwatch();
   ();
   var list=new List<string>();
   var t1 = Doing(1000, "1000");//1. Define the task   var t2 = Doing(1500, "1500");
   var t3 = Doing(1200, "1200");
   var tasks = new[] {t1, t2, t3};//2. Task Group   var process = (async tt =>//3. Wait for the task to end and save the value   {
    var result = await tt; 
    (result);
   });
   await (process);//4. Wait for complete processing   foreach (var i in list)//5. View the results   {
    (i);
   }
   ();
   ("time consuming:" + );   
  }

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.