1

So, I want to send the image from my WPF app to the Web API controller. When I get the image as BitmapImage and try to send it, I get the error "the calling thread cannot access this object because a different thread owns it". I don't see how am I modifying UI and why do I get the error. Here's the code:

WPF code:

private void BtnSendImage_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString();
        BitmapImage slika = null;

        if (ofd.ShowDialog() == true)
        {
            odabranaSlika = ofd.FileName;
            Uri adresa = new Uri(odabranaSlika, UriKind.Absolute);
            slika = new BitmapImage(adresa);
            ItemDAL idal = new ItemDAL();

            if (idal.SendImage(slika))
            {
                MessageBox.Show("Yay!");
            }
            else
            {
                MessageBox.Show("Awwww");
            }
        }
    }

Method SendImage from the ItemDAL class (the code stops at postResult.Wait() part):

public bool SendImage(BitmapImage bmp)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:52407/");
            var postResult = client.PostAsJsonAsync<BitmapImage>("api/values/postimage", bmp);
            postResult.Wait();

            var result = postResult.Result;
            if (result.IsSuccessStatusCode)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

What am I doing wrong? I know I'm not suppose to modify UI, unless it's from the main thread, bot how is this doing anything to the UI?

Alex
  • 35
  • 9
  • Try to `Freeze()` the BitmapImage before sending. Are you sure that PostAsJsonAsync is able to serialize it? Also note that the method should be awaited: `var result = await PostAsJsonAsync(...)`. Your method should then be declared as `public async Task SendImage(BitmapImage bmp)` and also be awaited. – Clemens Jan 09 '19 at 17:24
  • Just in case, see here for how to convert a BitmapImage to a byte array before posting: https://stackoverflow.com/a/29384523/1136211 – Clemens Jan 09 '19 at 17:30
  • @Clemens Thanks for the reply. I gave up on doing it now as it's not mandatory for the app. I'll do on a later stage and write here how did it went with those tweaks of yours. Cheers! – Alex Jan 09 '19 at 17:40
  • Does it really have to be json you send it as? https://stackoverflow.com/questions/19151793/uploading-a-file-from-a-wpf-application-to-a-web-api There's also uploadfileasync btw https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.uploadfileasync?view=netframework-4.7.2 – Andy Jan 09 '19 at 19:33

0 Answers0