C# Displaying a image in a form that is non-blocking to the rest of my code
-
13-09-2019 - |
Question
I know this is a rather broad question, but have a class that has a method to display an image and would like to use that method in a different piece of code to open up the image, but not have that method call be blocking.
So if I had the following snippet somewhere in a piece of code:
ImageClass MyImage = new ImageClass();
MyImage.DisplayImage(@"C:\SomeImage.jpg");
Console.Writeline("This is the line after displaying the image");
I would basically want the image to display and then proceed on to the Console Writeline. Do I have to create a new thread or process to do this? Thanks in advance.
Solution
Yes, you will need to use additional threads. I'm not as familiar with GDI, but you may need to run the non-UI code in a separate thread so that the UI code can run in the main UI thread. Something like the following:
ImageClass MyImage = new ImageClass();
MyImage.DisplayImage(@"C:\SomeImage.jpg");
ThreadPool.QueueUserWorkItem(new WaitCallback(new delegate(object o) {
Console.Writeline("This is the line after displaying the image");
}));
OTHER TIPS
Yes, creating a new thread and calling MyImage.DisplayImage(@"C:\SomeImage.jpg"); in that thread is the best way to do it.
PictureBox.LoadAsync() will load w/o blocking.