【问题标题】:How to handle the state of a method that runs in a BackgroundWorker如何处理在 BackgroundWorker 中运行的方法的状态
【发布时间】:2012-10-26 16:35:27
【问题描述】:

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

但我不确定这是否是一个好方法。关于如何在后台工作人员中处理报告过程,您有什么建议?什么是好的做法?我所做的是否是一个好的解决方法?

【问题讨论】:

  • 我宁愿做一个特定的类来传递给userState,但我想不出这有什么问题。
  • 我也想过这个,但是我真的懒得写一个新的类来为这个方法。

标签: c# multithreading refactoring backgroundworker


【解决方案1】:

我认为最好为你的操作结果创建一个类(我也会给这个类起更具描述性的名称,这样你就可以执行一些特定的操作):

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    相关资源
    最近更新 更多