1

現在取り組んでいるコードには、UI スレッドで実行されるメソッドがありました。しかし、時間がかかっていたので、BackgroundWorker に入れることにしました。コードは通常 UI を編集していましたが、スレッドを変更すると、UI スレッドでコントロールを編集する際に問題が発生しました。だから私がしたことは、メソッドがその状態を報告するようにし、ProgressChanged イベントで UI を変更することでした。進行状況を報告するために、このメソッドは「userState」という名前のオブジェクトを 1 つ受け取りますが、私の目的のために、複数のオブジェクトを報告する必要がありました。だから私は次のことをすることにしました:

        // Create a dictionary to keep method state for reporting.
        // "state" item represents a state type; "error", "update", "success".
        // "message"d item represents the message associated with the state.
        // "result" item represents the function result.
        // "invisiblecolumns" item represents the invisible columns this method finds.
        var methodState = new Dictionary<string, object> { { "state", "update" }, { "message", string.Empty }, 
                                                           { "result", null }, { "invisiblecolumns", null } };

しかし、これが良い方法かどうかはわかりません。バックグラウンド ワーカーでレポート プロセスを処理する方法について、あなたの提案は何ですか? 良い習慣とは何ですか?そして、私がしたことは良い回避策ですか?

4

1 に答える 1

4

操作結果のクラスを作成する方が良いと思います(また、このクラスにわかりやすい名前を付けて、特定の操作を実行しています):

public class OperationResult
{
    public OperationResult(OperationState state, string message = "")
    {
        State = state;
        Message = message;
    }

    public OperationState State { get; private set; }
    public string Message { get; private set; }
    // property for "result"
    // property for "invisiblecolumns
}

public enum OperationState
{
    Update,
    Success,
    Error
}

コードの可読性と保守性が大幅に向上し、IntellySense がサポートされます。比較:

 var result = (Dictionary<string, object>)e.UserState;
 if (result["slate"] == "update") // yep, misprint
    // do something
 labelMsg.Text = result["message"];
 // do you remember names of other entries?

 var result = (OperationResult)e.UserState;
 if (result.State == OperationState.Update)
    // do something
 labelMsg.Text = result.Message;
于 2012-10-26T08:15:43.040 に答える