C# 是否将任务转换为返回值的可等待任务?
这个代码有什么问题C# 是否将任务转换为返回值的可等待任务?,c#,C#,这个代码有什么问题 await Dispatcher.BeginInvoke(new Action(async () => { Task<BitmapImage> x = await Task.Run<Task<BitmapImage>>(async () => await savefile.Set_Image(Ntaban.Api.API_
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;
}));
wait Dispatcher.BeginInvoke(新操作(异步()=>
{
Task x=wait Task.Run(异步()=>wait savefile.Set_映像(Ntaban.Api.Api_server.Host+“/content/profile/”,St_mair.Directory_Main,lst.First().picAdr));
x、 等待();
imgProfile.Source=x.Result;
}));
方法集_图像为
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;
}
公共异步任务集\u映像(字符串位置\u在\u服务器中,字符串位置\u保存,字符串名称\u文件)
{
Ntaban.Api.Api_HttpClient apic=新的Ntaban.Api.Api_HttpClient();
字符串位置=要保存的位置+名称文件;
字符串location\u directory=要保存的位置;
if(Directory.Exists(location_Directory)==false)
{
CreateDirectory(位置\目录);
}
if(File.Exists(location)==false)
{
等待apic。下载\u文件\u异步(\u服务器中的位置\u+名称\u文件,位置,空);
}
BitmapImage s1=新的BitmapImage();
s1.BeginInit();
s1.UriSource=new System.Uri(保存位置+名称文件);
s1.EndInit();
返回s1;
}
如果基地是错误的,我希望有任务,但这个任务是可唤醒的。
我能做什么?在返回之前,调用在后台线程上创建的BitmapImage
上的Freeze()
方法:
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;
}
没有理由从同步方法调用
x.Wait()
或x.Result
。只需等待x即可。
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;
}