如何处理在BackgroundWorker中运行的方法的状态

时间:2012-10-26 08:03:15

标签: c# multithreading refactoring backgroundworker

我目前正在处理的代码有一个在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 } };

但我不确定这是否是一个很好的方法。您对如何处理后台工作人员的报告流程有何建议?什么是好习惯?那是我做了一个好的解决方法吗?

1 个答案:

答案 0 :(得分: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;