Reputation: 13019
recently I've been developing an application in Silverlight that uses uploading.
I use WebClient
class to communicate with an HttpHandler
that is in my server. The methods provided by WebClient
are asynchronous and use Event-based APM: having in mind that the scope of Silverlight is to have a fluid UI that doesn't blocks I wanted, for fun, to try making the calls synchronous.
AutoResetEvent _uploadedEvent = new AutoResetEvent(false);
foreach (var item in _fileInfos)
{
WebClient client = new WebClient();
client.OpenWriteCompleted += (sender, e) =>
{
try
{
using (FileStream fs = item.OpenRead())
using (Stream stream = y.Result)
{
while (true)
{
byte[] buffer = new byte[8192];
int readBytes = fs.Read(buffer, 0, buffer.Length);
if (readBytes == 0)
break;
stream.Write(buffer, 0, readBytes);
}
}
}
finally
{
_uploadedEvent.Set();
}
};
client.OpenWriteAsync(new Uri(_receiverUri));
_uploadedEvent.WaitOne();
}
This way to make the calls synchronous doesn't work in Silverlight but it does in WPF. Right now I'm noticing I'm not the only one to have this problem: https://stackoverflow.com/questions/3819650/silverlight-httprequest-thread-problem
Where do you think is the problem?
Thanks in advance.
AS-CII.
Upvotes: 1
Views: 794
Reputation: 118865
Silverlight needs to rendezvous with the UI thread in order to do the web request, but the UI thread is blocked on the WaitOne call, so you have a deadlock. (This can be construed as a Silverlight "feature".)
Upvotes: 5