﻿# 如何利用 Thread 類別限定某段程式碼的執行時間

上週我們有個案子發生程式 Hang 住的情況 (就是程式執行到某一行停止不動的情況)，程式執行到某個資料庫寫入動作的時間過長導致系統無法正常運作，由於資料庫那端我這邊無法快速修復，且此狀況又是偶發的，因此我就改以多執行緒的運作方式限制程式執行的時間，以免造成系統其他部分的正常運作，算是一個小小的開發技巧。

以下是一個簡單的範例，這是尚未修改程式碼之前的版本，用來闡述程式碼執行過久的狀況：

```csharp
using System;
using System.Threading;

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Start");
            Thread.Sleep(10 * 1000);
            Console.WriteLine("End");

            Console.WriteLine("Done!");
        }
    }
}
```

上述程式碼第 10 ~ 12 行總共執行了 10 秒鐘，如果我們要限制這三行不能執行超過 5 秒的話，就可以改用以下程式碼：

```csharp
using System;
using System.Threading;

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread t = new Thread(new ThreadStart(delegate()
            {
                Console.WriteLine("Start");
                Thread.Sleep(10 * 1000);
                Console.WriteLine("End");
            }));

            t.Start();

            Console.WriteLine("Waiting...");

            // 最多只能跑五秒!
            if (!t.Join(5 * 1000))
            {
                t.Abort();
            }
            Console.WriteLine("Done!");
        }
    }
}
```

如果你有多個程式碼片段要執行的話，也可以考慮使用 [ThreadPool 類別](http://msdn.microsoft.com/zh-tw/library/system.threading.threadpool.aspx) 的 [QueueUserWorkItem 方法](http://msdn.microsoft.com/zh-tw/library/system.threading.threadpool.queueuserworkitem.aspx) 來撰寫，記得像這種臨時性或不會重用(reuse)的程式碼都可以透過 [delegate](http://msdn.microsoft.com/en-us/library/900fyy8e.aspx) 撰寫[匿名方法](http://msdn.microsoft.com/zh-tw/library/0yw3tz5k.aspx)來簡化程式。

**相關連結**

-   [Thread 類別](http://msdn.microsoft.com/zh-tw/library/system.threading.thread.aspx)

-   [Thread.Join 方法 (Int32)](http://msdn.microsoft.com/zh-tw/library/6b1kkss0.aspx)
-   [Thread.Abort 方法](http://msdn.microsoft.com/zh-tw/library/system.threading.thread.abort.aspx)

-   [ThreadPool 類別](http://msdn.microsoft.com/zh-tw/library/system.threading.threadpool.aspx)
-   [delegate (C# Reference)](http://msdn.microsoft.com/en-us/library/900fyy8e.aspx)
-   [匿名方法 (C# 程式設計手冊)](http://msdn.microsoft.com/zh-tw/library/0yw3tz5k.aspx) / [Anonymous Methods (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx)
