Reputation: 538
I have this method for receiving a file.
public Task Download(IProgress<int> downloadProgress)
{
return Task.Run
(
async () =>
{
var counter = 0;
var buffer = new byte[1024];
while (true)
{
var byteCount = await _networkStream.ReadAsync(buffer, 0, buffer.Length);
counter += byteCount;
downloadProgress.Report(counter);
if (byteCount != buffer.Length)
break;
}
}
);
}
Then in the UI I call it like this:
await Download(progress);
where progress is simply updating a label.
When I run, the UI will be blocked (but after some time it will correctly update the label). I don't understand why, shouldn't Task.Run() create a new thread?
How do I fix this please?
Upvotes: 2
Views: 152
Reputation: 7604
You are calling downloadProgress.Report
on an infinite loop without any pause in execution. My educated guess is this means every time execution time is available on the UI thread, the non-UI thread is requesting an operation which will require the UI thread's time (as demanded by the synchronisation context) and therefore clogging it up with invocations.
Essentially, rather than blocking the UI thread with one long execution, you may be blocking it with an un-ending stream of tiny ones.
Try putting a Thread.Sleep(10)
in your 'spinlock' while(true) { ... }
loop and see if that alleviates the issue.
Upvotes: 4