.NET Frameworkでメソッドをタイムアウトさせる方法

http://msdn.microsoft.com/msdnmag/issues/05/07/NETMatters/

MSDN Magazineにある、.NET関連のQ&Aみたいなページ。
今回扱ってるテーマは二つ。

  • Stringを変換してStreamにする方法
  • メソッドの実行を一定時間でタイムアウトさせる方法

タイムアウトの方が面白そうだったので、ちょっと試してみた。
下のページにあるタイムアウト用のクラスを使用する。Figure.2を参照。
http://msdn.microsoft.com/msdnmag/issues/05/07/NETMatters/default.aspx?fig=true#fig2
使い方はこんな感じになる。

using System;
using NetMatters;

namespace Console1
{
    class Program
    {
        delegate int MyDelegate(int input);
        static void Main(string[] args)
        {
            int exectime = 10;//メソッドの実行にかかる時間
            int waittime = 10;//タイムアウトするまでの許容時間
            if (args.Length > 1)
            {
                exectime = Convert.ToInt32(args[0]);
                waittime = Convert.ToInt32(args[1]);
            }
            Console.WriteLine("ExecTime {0:d}", exectime);
            Console.WriteLine("WaitTime {0:d}", waittime);
            bool aborted;//abortされたかどうか
            //メソッドの実行
            object obj = TimedOperation.Invoke(
                TimeSpan.FromSeconds(waittime), out aborted, 
                new MyDelegate(SomeMethod), new object[] { exectime });
            //結果
            Console.WriteLine(obj == null ? "Nothing Returned" : obj.ToString());
            Console.WriteLine(aborted ? "Aborted" : "Completed");
        }
        //時間制限付きで実行するメソッド
        static int SomeMethod(int input)
        {
            System.Threading.Thread.Sleep(input * 1000);
            return input;
        }
    }
}

実行結果は以下の通り。
それぞれ、時間内に終了するケースとタイムアウトするケース。

C:\VSS\VSSTEST\AWSTest\Console1\bin\Debug>console1.exe 1 5
ExecTime 1
WaitTime 5
1
Completed

C:\VSS\VSSTEST\AWSTest\Console1\bin\Debug>console1.exe 5 1
ExecTime 5
WaitTime 1
Nothing Returned
Aborted

C:\VSS\VSSTEST\AWSTest\Console1\bin\Debug>

Webサービスなんかで使えそうなのかな。

ちなみにRubyだと、

timeout(10) { 
    execSomeMethod(some args)
}

みたいに超簡単に書けるんだが、C#にそれを求めてはいけない。
プログラミング言語 Ruby リファレンスマニュアル