0

this seems to be quite trivial and I saw some similar questions online but I couldn't get it to work anyways. I have a C# thread that waits for an incoming TCP client then reads an image over TCP. All of this works fine but I can't get the thread to display the image.

Here's what I have. In the UI Thread:

public partial class ReadImagePage : Page {
    //...
    listener = new TcpListener(IPAddress.Any, 11114);
    listenThread = new Thread(() => AsyncAccept(this, listener));
    listenThread.Start();
    //...
}

In the AsyncAccept:

private void AsyncAccept(ReadPassportPage readPassportPage, TcpListener listener)
{
    listener.Start();
    TcpClient client = listener.AcceptTcpClient();
    var image = new BitmapImage();
    // read bitmap from tcp...
}

I now want to set the image to an Image within my WPF page. I tried multiple variations of this. Even passing the page object to the thread. But I kept getting an InvalidOperationException exception because the Thread is not allowed to access the UI element.

Application.Current.Dispatcher.BeginInvoke(new Action(delegate() {
     signatureImage.Source = image;
}));

How can I get this to work? Any help is greatly appreciated. Thanks in advance.

Androidicus
  • 1,688
  • 4
  • 24
  • 36
  • "But I kept getting an exception." Well. What is it? – Glorin Oakenfoot Nov 12 '15 at 22:47
  • @GlorinOakenfoot InvalidOperationException. I updated my question. – Androidicus Nov 12 '15 at 22:49
  • 1
    Try adding image.Freeze() before calling your BeginInvoke() – Glorin Oakenfoot Nov 12 '15 at 22:52
  • @GlorinOakenfoot Awesome, that did the trick. Thanks a lot! – Androidicus Nov 12 '15 at 22:56
  • For related topics with additional useful information in your scenario, see also [Convert memory stream to BitmapImage?](https://stackoverflow.com/q/5346727), [Create and update UI elements Async Wpf](https://stackoverflow.com/q/15506527), [Best way to constantly draw large numbers of bitmaps in WPF?](https://stackoverflow.com/q/5093110), [Download BitmapImage using Task Parallel Library](https://stackoverflow.com/q/5469968), and [Thread cannot access the object](https://stackoverflow.com/q/11226806) – Peter Duniho Nov 13 '15 at 00:56

0 Answers0