C# 在另一个线程中调用HttpWebRequest作为任务类的UI-避免处置在任务范围中创建的对象
我想在另一个线程上调用HttpWebRequest作为UI,因为我必须发出200请求或服务器和下载的图像 我的设想是,我在服务器上发出请求,创建映像并返回映像。这是我用另一根线做的。我使用任务类,但它对任务范围中创建的所有对象自动调用Dispose方法。所以我从这个方法返回null对象C# 在另一个线程中调用HttpWebRequest作为任务类的UI-避免处置在任务范围中创建的对象,c#,multithreading,httpwebrequest,dispose,task,C#,Multithreading,Httpwebrequest,Dispose,Task,我想在另一个线程上调用HttpWebRequest作为UI,因为我必须发出200请求或服务器和下载的图像 我的设想是,我在服务器上发出请求,创建映像并返回映像。这是我用另一根线做的。我使用任务类,但它对任务范围中创建的所有对象自动调用Dispose方法。所以我从这个方法返回null对象 public BitmapImage CreateAvatar(Uri imageUri, int sex) { if (imageUri == 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;
}
如何避免它?谢谢你不用等任务了
public BitmapImage CreateAvatar(Uri imageUri, int sex)
{
BitmapImage image = null;
new Task(() =>
{
....
}).Start();
return image; // But the task is still running ...
}
要解决这个问题,您必须等待()完成任务,但是最好不要在这里使用任务
必须在更广泛的计划中制定出真正的解决方案 当您可以更轻松地调用时,为什么要使用
Task
?或者干脆放弃HttpWebRequest的复杂性,使用它。你认为什么是自动处理对象?我觉得不太可能。现在你返回image
它还没有填满。您的方法将始终返回null
,任务将填充一个无法访问(捕获)的变量。