You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何声明无需接收参数的Progress进度指示器实例?

解决方案

.NET 内置的IProgress<T>泛型接口默认要求必须携带进度参数,没有原生的无参数实现,你可以通过自定义封装的方式完全去掉无效的占位参数,且封装后的实现和原生Progress<T>的行为完全一致,支持UI线程安全回调。

第一步:自定义无参数进度接口和实现

// 定义无参数的进度通知接口
public interface IProgress
{
    void Report();
}

// 实现对应进度类,兼容原生Progress的线程上下文逻辑
public class Progress : IProgress
{
    private readonly Action _callback;
    private readonly SynchronizationContext _syncContext = SynchronizationContext.Current ?? new SynchronizationContext();

    public Progress(Action callback)
    {
        _callback = callback ?? throw new ArgumentNullException(nameof(callback));
    }

    public void Report()
    {
        _syncContext.Post(state => _callback.Invoke(), null);
    }
}

第二步:替换原有声明逻辑

// 不再需要无用的int参数和占位值
var progressIndicator = new Progress(() =>
{
    progressBar.PerformStep();
});

第三步:修改异步方法签名和调用逻辑

private async Task AsyncMtdCAll(int val, IProgress progress)
{
    // 原有业务逻辑
    // .....    
    // .....
    // 直接调用无参Report即可,无需传占位值
    progress.Report(); 
}

如果你不想额外封装类,也可以用折衷方案:直接使用Progress<object>,传null作为占位值,不过自定义实现的代码可读性更高,没有冗余逻辑。


内容的提问来源于stack exchange,提问作者variable

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 20:54:02