c# – IP进程同步
发布时间:2020-12-15 04:09:00 所属栏目:百科 来源:网络整理
导读:我在C#中有以下 public static void Main(){ var result = Foo(new Progressint(i = Console.WriteLine("Progress: " + i))); Console.WriteLine("Result: " + result); Console.ReadLine();}static int Foo(IProgressint progress){ for (int i = 0; i 10;
我在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()方法在 只是不要使用进度< T>在这里上课,没有意义.您在控制台模式应用程序中没有UI线程安全问题;控制台类已经是线程安全的.固定: static int Foo() { for (int i = 0; i < 10; i++) Console.WriteLine("Progress: {0}",i); return 1001; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |