最近我在 Silverlight 中开发了一个使用上传的应用程序。
我使用 WebClient
类与服务器中的 HttpHandler
进行通信。 WebClient
提供的方法是异步的,并使用基于事件的 APM:考虑到 Silverlight 的范围是拥有一个流畅的 UI,我想要,为了好玩,尝试制作调用同步。
代码
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();
}
问题
这种使调用同步的方法在 Silverlight 中不起作用,但在 WPF 中有效。 现在我注意到我不是唯一遇到这个问题的人:https://stackoverflow.com/questions/3819650/silverlight-httprequest-thread-problem
您认为问题出在哪里?
提前致谢。
AS-CII。
最佳答案
Silverlight 需要与 UI 线程会合才能执行 Web 请求,但 UI 线程在 WaitOne 调用时被阻塞,因此出现了死锁。 (这可以解释为 Silverlight 的“功能”。)
关于c# - Silverlight 4 线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4203590/