SoFunction
Updated on 2025-03-07

C# Summary of several ways to determine whether the code is executing timeout

c# determines whether the code is executed timeout

1. Use the delegation

delegate void dg();
dg dgCase;
void method()
{
     dgCase = () =>
     {
          (10000);
          ("The code is completed!");
     };
     WaitHandle wh = (null, null).AsyncWaitHandle;
     if (!(3000))
     {
          ("It's been 3 seconds since execution!");
     }
     return;
}

2. Use Task

Task t = new Task(() => {
     (10000);
     ("The code is completed!");
});
();
if(!(3000))
{
     ("It's been 3 seconds since execution!");
}
return;

3. Use Timer

void method()
{
      time = new (3000) { Enabled = true };
      += (x, j) =>
     {
          ("It's been 3 seconds since execution!");
          ();
     };
     (10000);
     ("The code is completed!");
     ();
     return;
}

4. Use Thread

void ThreadMethod()
{
     Thread t = new Thread(()=>
     {
          (10000);
          ("The code is completed!");
     });
     ();
     bool isOver = (3000);
     if(!isOver)
     {
          ("It's been 3 seconds since execution!");
     }
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.