c# - IProgress<T> synchronization -
i have following in 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) { (int = 0; < 10; i++) progress.report(i); return 1001; } some outputs of main are:
first run:
result: 1001 progress: 4 progress: 6 progress: 7 progress: 8 progress: 9 progress: 3 progress: 0 progress: 1 progress: 5 progress: 2 second run:
progress: 4 progress: 5 progress: 6 progress: 7 progress: 8 progress: 9 progress: 0 progress: 1 progress: 2 result: 1001 progress: 3 etc...
for every run, output different. how can synchronize these methods progress displayed in order reported 0,1,...9 followed result 1001. want output this:
progress: 0 . . . progress: 9 result: 1001
the progress<t> class uses synchronizationcontext.current property post() progress update. done ensure progresschanged event fires on ui thread of program safe update ui. necessary safely update, say, progressbar.value property.
the problem console mode app doesn't have synchronization provider. not winforms or wpf app. synchronization.current property has default provider, post() method runs on threadpool. without interlocking @ all, threadpool thread gets report update first entirely unpredictable. there isn't way interlock either.
just don't use progress<t> class here, there no point. don't have ui thread safety problem in console mode app; console class thread-safe. fix:
static int foo() { (int = 0; < 10; i++) console.writeline("progress: {0}", i); return 1001; }
Comments
Post a Comment