0

非同期で実行されている Windows svc があります (メソッドとそのパラメーターを編集して非同期にしました)

ただし、非同期で実行したいタスクを呼び出し (サービス/サーバーへの呼び出し)、UI を更新します (backgroundworker で ReportProgress() を使用)。これはすべて、backgroundworker の dowork() メソッドで行われます。 )。ただし、結果を取得するために Endxxx メソッドを呼び出しますが、問題は、私のコードが次のように見えるべきではないということです。

while (!asyncresult.IsCompleted) { // Do all UI updating etc here... }

// Call endXXX here.

ただし、この方法では UI がロックされます。現時点では、私のコードは次のようになっています (UI をロックしません)。

 IAsyncResult res = null;

                try
                {

                    res = serviceX.BeginXXX(ResultCallBack, "");
                }
                catch (FaultException<ManagementException> managementEx)
                {
                    Logger.Error(managementEx.Detail.ToString());
                    MessageBox.Show("Could not add printer. See log.");
                }



                    InstallBackgoundWorker.ReportProgress(90);
                    InstallBackgoundWorker.ReportProgress(91);
                    InstallBackgoundWorker.ReportProgress(93);

                    InstallBackgoundWorker.ReportProgress(94);
                    InstallBackgoundWorker.ReportProgress(95);
                    InstallBackgoundWorker.ReportProgress(96);
                    InstallBackgoundWorker.ReportProgress(97);



                    if (res.IsCompleted)
                    {
                        ResultCallBack(res);
                    }
                    InstallBackgoundWorker.ReportProgress(100);

これは正しいです?私には間違っているようです。

4

2 に答える 2

0

非同期パターンを正しく使用しているかどうかはわかりません。次のようになります。

void Start()
{
    System.IO.Stream s = ...;
    byte[] buf = ...;

    // start the IO.

    s.BeginRead(buf, 0, buf.Length, res =>
        {
            // this gets called when it's finished,
            // but you're in a different thread.

            int len = s.EndRead(res);

            // so you must call Dispatcher.Invoke
            // to get back to the UI thread.

            Dispatcher.Invoke((Action)delegate
                {
                    // perform UI updates here.
                });
        }, null);

    // the IO is started (and maybe finished) here,
    // but you probably don't need to put anything here.
}

Streamあなたのオブジェクトの署名がわからないので、で書かれていますが、うまくいけばアイデアが得られます! Begin メソッドを呼び出した直後ではなく、指定したコールバックで操作の完了を処理する必要があります。IsCompletedプロパティをポーリングする必要はありません。

于 2011-05-11T23:20:13.250 に答える