c# - System.Progress wrong invocation order -


i'm trying display download progress using httpclient. use system.progress<t>. code looks this:

long totalread = 0l; var buffer = new byte[1024]; bool ismoretoread = true; ulong total = (ulong)response.content.headers.contentlength;  while (ismoretoread) {     int read = await stream.readasync(buffer, 0, buffer.length);     if (read == 0)         ismoretoread = false;     else     {         var data = new byte[read];         buffer.tolist().copyto(0, data, 0, read);         totalread += read;         progress.report((int) (totalread*1d / total * 1d * 100) );     } } 

assume subscribing looks this:

var progress = new progress<int>(); progress.progresschanged += (sender, i) => console.writeline(i); client.download(file, progress).wait(); 

but result, progress order inconsistent, this: 10, 20, 30, 70, 15, 90, 100, 80.

is default delegate's behaviour, or there's reason?

progress<t>.report asynchronous; mean, report method not raise progresschanged event synchronously before returns.

progress<t> class captures synchronizationcontext , posts invocation of progresschanged event captured context.

when used in single threaded context winforms, wpf, code work expected.

in console app, there not synchronizationcontext , progress<t> posts invocation default synchronizationcontext delegates threadpool. threadpool doesn't guarantee order, that's reason don't see synchronous result.

i believe you're testing code in console app or similar otherwise nothing wrong code.

if need synchronous version of iprogress<t>, have roll own.


Comments

Popular posts from this blog

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

android - How to create dynamically Fragment pager adapter -

1111. appearing after print sequence - php -