此代码有什么问题
await Dispatcher.BeginInvoke(new Action(async () =>
{
Task<BitmapImage> x = await Task.Run<Task<BitmapImage>>(async () => await savefile.Set_Image(Ntaban.Api.API_server.Host + "/content/profile/", St_Major.Directories.Directory_Main, lst.First().picAdr));
x.Wait();
imgProfile.Source = x.Result;
}));
,方法Set_Image是
public async Task<BitmapImage> Set_Image(string location_in_server, string location_to_save, string name_file)
{
Ntaban.Api.API_HttpClient apic = new Ntaban.Api.API_HttpClient();
string location = location_to_save + name_file;
string location_directory = location_to_save;
if (Directory.Exists(location_directory) == false)
{
Directory.CreateDirectory(location_directory);
}
if (File.Exists(location) == false)
{
await apic.download_file_async(location_in_server + name_file, location, null);
}
BitmapImage s1 = new BitmapImage();
s1.BeginInit();
s1.UriSource = new System.Uri(location_to_save + name_file);
s1.EndInit();
return s1;
}
如果基础错误我喜欢有任务,但这项任务是可以理解的。 我该怎么办?
答案 0 :(得分:1)
在返回之前调用您在后台线程上创建的Freeze()
上的BitmapImage
方法:
public async Task<BitmapImage> Set_Image(string location_in_server, string location_to_save, string name_file)
{
Ntaban.Api.API_HttpClient apic = new Ntaban.Api.API_HttpClient();
string location = location_to_save + name_file;
string location_directory = location_to_save;
if (Directory.Exists(location_directory) == false)
{
Directory.CreateDirectory(location_directory);
}
if (File.Exists(location) == false)
{
await apic.download_file_async(location_in_server + name_file, location, null);
}
BitmapImage s1 = new BitmapImage();
s1.BeginInit();
s1.UriSource = new System.Uri(location_to_save + name_file);
s1.EndInit();
s1.Freeze();
return s1;
}
等待UI应用程序中的Set_Image方法:
public async void Button_Click(object sender, RoutedEventArgs e)
{
string locationA = Ntaban.Api.API_server.Host + "/content/profile/";
string locationB = St_Major.Directories.Directory_Main;
string name = lst.First().picAdr;
BitmapImage bitMapImage = await Task.Run(async () => await savefile.Set_Image(locationA, locationB, name));
imgProfile.Source = bitMapImage;
}