0

タスク。

内部で 2 つの長時間関数を実行するメソッドが 1 つあります。

ここでオブジェクトのロックについて話しているわけではありません。これらの関数は独立しており、読み取り専用で使用される同じパラメーターのみを持ちます。

スレッド内で実行する関数が 1 つ必要です。

private static ManualResetEvent mre = new ManualResetEvent(false);
private Result result;

{
 BackgroundWorker bw = new BackgroundWorker();
 bw.DoWork += new DoWorkEventHandler(bw_DoWork);
 bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
 bw.RunWorkerAsync(new BackgroundWorkerArgument(bitmap, image));

Rectangle rectangle = DetectRectangle(bitmapClone));
mre.WaitOne();
mre.Reset();

<another code, dont bother>
}

void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        result= (Result)e.Result;
    }

    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorkerArgument argument = (BackgroundWorkerArgument)e.Argument;
        e.Result = CreateResult(argument.Bitmap, argument.Image);
        mre.Set();
    }

問題。

<another code, dont bother>i do の直後に実行されますSet()。大丈夫です。

しかし、bw_RunWorkerCompletedその後を実行します。これは、結果変数にnullがあることを意味しますが、スレッドの関数の結果を含めたいです。

コードを作り直す方法 -result= (Result)e.Result次の行の前に実行する必要がありWaitOne()ますか?

BackgroundWorkerおそらく私はスレッドを使用する必要がありますか?.NET 2.0 を使用しています。

4

0 に答える 0