2

タスクを実行するために2つのスレッドをバックグラウンドで実行しようとしています。スレッドを順番に作成して、プログラムの実行を続行する必要があります。ただし、2番目のスレッドは、最初のスレッドが終了したときにのみ機能するように実行する必要があります。また、もう1つの説明。このソリューションをWPFアプリケーションで使用したいと考えています。UIフィードバックは必要ありません。必要なのは、最初のタスクからのステータスの更新だけです。すべてを1つのスレッドで実行すれば、問題ないことに同意します。ただし、ユーザーがこのスレッドを作成した画面を離れた場合でも、より多くのことを個別に実行する2番目のスレッドが必要です。

サンプルは次のとおりです。

class Program
{

    static string outValue;
    static bool _isFinished = false;

    static void Main(string[] args)
    {
        ThreadStart thread1 = delegate()
        {
            outValue = AnotherClass.FirstLongRunningTask();
            // I need to set the _isFinished after the long running finishes..
            // I cant wait here because I need to kick start the next thread and move on.
            // 
        };
        new Thread(thread1).Start();

        ThreadStart thread2 = delegate()
        {
            while (!_isFinished)
            {
                Thread.Sleep(1000);
                Console.WriteLine("Inside the while loop...");
            }
            if (!string.IsNullOrEmpty(outValue))
            {
                // This should execute only if the _isFinished is true...
                AnotherClass.SecondTask(outValue);    
            }

        };
        new Thread(thread2).Start();

        for (int i = 0; i < 5000; i++)
        {
            Thread.Sleep(500);
            Console.WriteLine("I have to work on this while thread 1 and thread 2 and doing something ...");    
        }    
        Console.ReadLine();

    }



}


public class AnotherClass
{
    public static string FirstLongRunningTask() 
    {
        Thread.Sleep(6000);
        return "From the first long running task...";
    }

    public static void SecondTask(string fromThread1) 
    {
        Thread.Sleep(1000);
        Console.WriteLine(fromThread1);
    }
}

_isFinishedはどこに設定しますか?
BackgroundWorkerスレッドを使用できません。どんな助けでも大歓迎です。

4

2 に答える 2

2

スレッドが別のスレッドが終了したときにのみ開始できる場合は、非常に簡単な解決策があります。最初のスレッドでコード全体を実行します。

Task.ContinueWith同じに対してより多くの作業をキューに入れるために使用できますTask

于 2012-07-24T18:10:08.287 に答える
2

を呼び出すだけでthread1.Join()、終了するまでブロックされthread1ます。

ただし、これを行うためのより良い方法は多数あります。
代わりに、TPLとTaskクラスを使用する必要があります。

于 2012-07-24T17:45:57.177 に答える