Wednesday 15 September 2010

c# - IProgress not firing -



c# - IProgress<T> not firing -

i have next snipped of code:

var progress = new progress<string>(); var count = 0; progress.progresschanged += (o, transferprogress) => ++count; (var = 0; < 10; i++) { ((iprogress<string>)progress).report(i.tostring(cultureinfo.invariantculture)); } console.writeline(count);

in case, count variable never gets incremented. why that?

update: events seems firing "late" (as have pointed below). give more context, snippet of code placed in win forms app in button click event handler. no matter did in handler (i.e. set sleep x seconds), until button click handler wasn't finished executing events not fire. how can around "timely" events?

from progress<t> documentation:

any handler provided constructor or event handlers registered progresschanged event invoked through synchronizationcontext instance captured when instance constructed. if there no current synchronizationcontext @ time of construction, callbacks invoked on threadpool.

what happening here have synchronization context, , callbacks beingness delayed until time later, depending on behavior of particular synchronization context governs execution of code.

note if not running under synchronization context, not guaranteed count == 10 next loop body, because thread pool may not have yet executed of callbacks.

further, since variable not declared volatile current thread may not observe changes made thread since runtime/jit allowed cache values not perchance alter in single-threaded context. safe want utilize interlocked.increment(ref count) within of callback in case 2 callbacks executed simultaneously, because ++count not atomic operation. (this relevant if callbacks getting dispatched via thread pool.)

tl;dr version "welcome concurrency."

c# .net .net-4.5

No comments:

Post a Comment