在另一个线程中调用 HttpWebRequest 作为具有 Task 类的 UI - 避免处置在 Task 范围内创建的对象
我想在另一个线程上调用 HttpWebRequest 作为 UI,因为我必须发出 200 个请求或服务器并下载图像。
我的场景是,我在服务器上发出请求,创建图像并返回图像。这是我在另一个线程中做的。我使用 Task 类,但它会自动对任务范围内创建的所有对象调用 Dispose 方法。所以我从此方法返回 null 对象。
public BitmapImage CreateAvatar(Uri imageUri, int sex)
{
if (imageUri == null)
return CreateDefaultAvatar(sex);
BitmapImage image = null;
new Task(() =>
{
var request = WebRequest.Create(imageUri);
var response = request.GetResponse();
using (var stream = response.GetResponseStream())
{
Byte[] buffer = new Byte[response.ContentLength];
int offset = 0, actuallyRead = 0;
do
{
actuallyRead = stream.Read(buffer, offset, buffer.Length - offset);
offset += actuallyRead;
} while (actuallyRead > 0);
image = new BitmapImage
{
CreateOptions = BitmapCreateOptions.None,
CacheOption = BitmapCacheOption.OnLoad
};
image.BeginInit();
image.StreamSource = new MemoryStream(buffer);
image.EndInit();
image.Freeze();
}
}).Start();
return image;
}
如何避免呢?感谢
I would like call HttpWebRequest on another thread as UI, because I must make 200 request or server and downloaded image.
My scenation is that I make a request on server, create image and return image. This I make in another thread. I use Task class, but it call automaticaly Dispose method on all object created in task scope. So I return null object from this method.
public BitmapImage CreateAvatar(Uri imageUri, int sex)
{
if (imageUri == null)
return CreateDefaultAvatar(sex);
BitmapImage image = null;
new Task(() =>
{
var request = WebRequest.Create(imageUri);
var response = request.GetResponse();
using (var stream = response.GetResponseStream())
{
Byte[] buffer = new Byte[response.ContentLength];
int offset = 0, actuallyRead = 0;
do
{
actuallyRead = stream.Read(buffer, offset, buffer.Length - offset);
offset += actuallyRead;
} while (actuallyRead > 0);
image = new BitmapImage
{
CreateOptions = BitmapCreateOptions.None,
CacheOption = BitmapCacheOption.OnLoad
};
image.BeginInit();
image.StreamSource = new MemoryStream(buffer);
image.EndInit();
image.Freeze();
}
}).Start();
return image;
}
How avoid it? Thank
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不用等待任务。
要解决这个问题,您必须在任务上使用 Wait(),但最好不要在这里使用任务。
真正的解决方案必须在更广泛的计划中制定。
You don't wait for the Task.
To solve it, you would have to Wait() on the Task but then it would be better not to use a task at all here.
A real solution will have to be worked out in the wider program.
当您可以更轻松地调用 HttpWebRequest.BeginGetResponse?或者完全放弃
HttpWebRequest
的复杂性并使用 WebClient.DownloadDataAsync。Why use
Task
when you can more easily call HttpWebRequest.BeginGetResponse? Or just forego the complexity ofHttpWebRequest
altogether and use WebClient.DownloadDataAsync.