1

我目前正在处理的代码有一个在 UI 线程中运行的方法。但这需要很长时间,所以我决定将它放在 BackgroundWorker 中。代码通常在编辑 UI,当我更改线程时,出现了在 UI 线程中编辑控件的问题。所以我所做的是让方法报告它的状态,并在 ProgressChanged 事件中更改 UI。为了报告进度,此方法采用一个名为“userState”的对象,但出于我的目的,我必须报告多个对象。所以我选择执行以下操作:

        // 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 回答