Thread timeout in c#

前端 未结 7 706
春和景丽
春和景丽 2021-01-11 18:41

I\'m new to threading in C#. Is there anyway of setting a timeout for a thread without blocking the calling thread (in C# 3.5)?

If not, is it logical to execute a fu

7条回答
  •  盖世英雄少女心
    2021-01-11 19:32

    The easiest thing to do is to call Thread.Join at safe points from your main thread and pass in the amount of time you want to wait for the join to occur.

    public static void Main()
    {
      TimeSpan timeout = TimeSpan.FromSeconds(30);
      Thread thread = new Thread(() => { ThreadMethod(); });
      thread.Start();
      DateTime timeStarted = DateTime.UtcNow;
      DoSomeWorkOnThisThread();
      // We are at a safe point now so check the thread status.
      TimeSpan span = DateTime.UtcNow - timeStarted; // How long has the thread been running.
      TimeSpan wait = timeout - span; // How much more time should we wait.
      if (!thread.Join(wait))
      {
        thread.Abort(); // This is an unsafe operation so use as a last resort.
      }
    }
    

提交回复
热议问题