-1

what is wrong with this code

 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;
                    }));

and the method Set_Image is

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;
    }

if the base is wrong i like to have task but this task is awatable . what can i do?

amir jahany
  • 45
  • 1
  • 11

1 Answers1

1

Call the Freeze() method on the BitmapImage that you create on the background thread before you return:

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;
}

And await the Set_Image method in your UI application:

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;
}
mm8
  • 163,881
  • 10
  • 57
  • 88