我在C#中有以下
public static void Main() { var result = Foo(new Progress<int>(i => Console.WriteLine("Progress: " + i))); Console.WriteLine("Result: " + result); Console.ReadLine(); } static int Foo(IProgress<int> progress) { for (int i = 0; i < 10; i++) progress.Report(i); return 1001; }
主要产品有:
第一次运行:
Result: 1001 Progress: 4 Progress: 6 Progress: 7 Progress: 8 Progress: 9 Progress: 3 Progress: 0 Progress: 1 Progress: 5 Progress: 2
第二次运行:
Progress: 4 Progress: 5 Progress: 6 Progress: 7 Progress: 8 Progress: 9 Progress: 0 Progress: 1 Progress: 2 Result: 1001 Progress: 3
等等…
对于每次运行,输出是不同的.如何同步这些方法,以便按照报告的顺序显示进度0,1,… 9,后跟结果为1001.我希望输出如下所示:
Progress: 0 . . . Progress: 9 Result: 1001
解决方法
Progress<T>
类使用
SynchronizationContext.Current
属性到
Post()
进度更新.这样做是为了确保
ProgressChanged
事件在程序的UI线程上触发,因此可以安全地更新UI.有必要安全更新,比如
ProgressBar.Value
的财产.
控制台模式应用程序的问题是它没有同步提供程序.不像Winforms或WPF应用程序. Synchronization.Current属性具有默认提供程序,其Post()方法在ThreadPool
上运行.没有任何联锁,哪个ThreadPool线程首先报告其更新是完全不可预测的.没有任何好的互锁方式.
只是不要使用进度< T>在这里上课,没有意义.您在控制台模式应用程序中没有UI线程安全问题;控制台类已经是线程安全的.固定:
static int Foo() { for (int i = 0; i < 10; i++) Console.WriteLine("Progress: {0}",i); return 1001; }