質問

私は、3秒未満かかるはずのDoworkタスクの世話をするためにスレッドをスポーンしようとしています。 Doworkの内部は15秒かかります。 Doworkを中止し、コントロールをメインスレッドに戻したいです。次のようにコードをコピーしましたが、機能していません。 Doworkを中止する代わりに、それでもDoworkを終了し、コントロールをメインスレッドに戻します。私は何が間違っているのですか?

class Class1
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    /// 

    private static System.Threading.ManualResetEvent[] resetEvents;

    [STAThread]
    static void Main(string[] args)
    {
        resetEvents = new ManualResetEvent[1];

        int i = 0;

        resetEvents[i] = new ManualResetEvent(false);
        ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork),(object)i);


        Thread.CurrentThread.Name = "main thread";

        Console.WriteLine("[{0}] waiting in the main method", Thread.CurrentThread.Name);

        DateTime start = DateTime.Now;
        DateTime end ;
        TimeSpan span = DateTime.Now.Subtract(start);


        //abort dowork method if it takes more than 3 seconds
        //and transfer control to the main thread.
        do
        {
            if (span.Seconds < 3)
                WaitHandle.WaitAll(resetEvents);
            else
                resetEvents[0].Set();


            end = DateTime.Now;
            span = end.Subtract(start);
        }while (span.Seconds < 2);



        Console.WriteLine(span.Seconds);


        Console.WriteLine("[{0}] all done in the main method",Thread.CurrentThread.Name);

        Console.ReadLine();
    }

    static void DoWork(object o)
    {
        int index = (int)o;

        Thread.CurrentThread.Name = "do work thread";

        //simulate heavy duty work.
        Thread.Sleep(15000);

        //work is done..
        resetEvents[index].Set();

        Console.WriteLine("[{0}] do work finished",Thread.CurrentThread.Name);
    }
}
役に立ちましたか?

解決

全て プールされたスレッド バックグラウンドスレッドです。つまり、アプリケーションの前景スレッドが終了すると自動的に終了します。

ループを変更し、リセットイベントを削除しました。

     //abort dowork method if it takes more than 3 seconds 
     //and transfer control to the main thread. 
     bool keepwaiting = true;
     while (keepwaiting)
     {
        if (span.Seconds > 3)
        {
           keepwaiting = false;
        }

        end = DateTime.Now;
        span = end.Subtract(start);
     }

他のヒント

[STAThread] シングルスレッドアパートメントです。試す [MTAThread] マルチスレッドアパートメントです。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top