总而言之,我有一个昂贵的任务,我使用.NET4.5 下的async
/关键字来完成。我通过课程await
从后台线程报告进度。Progress<T>
IProgress<T>
我作为类型传入的对象是ProgressInfo
我作为单例类创建的,以避免在运行期间多次创建和处置这种类型的对象的开销。班级是
public class ProgressInfo : IDisposable
{
public static ProgressInfo instance = null;
public WorkbookProgressInfo workbookinfo { get; set; }
public string progressMessage { get; set; }
public int progressPercentage { get; set; }
// Default constructor which has a few overloads
// for the class members above.
protected ProgressInfo()
{
}
...
// The default instance creator for the class.
// This also has overloads to allow changes to the
// class variables.
public static ProgressInfo Instance()
{
if (instance == null)
instance = new ProgressInfo();
return instance;
}
...
}
我通过该方法报告进度ReportProgress
并将我的设置IProgress<ProgressInfo>
为
IProgress<CostEngine.ProgressInfo> progressIndicator =
new Progress<CostEngine.ProgressInfo>(ReportProgress);
来自后台线程的报告通常是使用全局ProgressInfo progressInfo
和全局IProgress<ProgressInfo> progressIndicator
类似的
...
progressInfo = new ProgressInfo.Instance(workbookinfo, message, n);
progressIndicator.Report(progressInfo);
...
问题是,对于小且执行速度快的运行,ProgressInfo
传入的对象在执行时会ReportProgress
发生变化ReportProgress
,所以我测试
if (progressInfo.workbookinfo != null)
{
// Do stuff <- here progressInfo.workbookinfo is changing to null!
}
我怎样才能避免这个问题,同时将报告进度的费用保持在最低限度?
谢谢你的时间。