Skip to main content
 首页 » 编程设计

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

2024年02月20日18kenshinobiy

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

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

请您参考如下方法:

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

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;