Kage Kage - 1 year ago 145
C# Question

Windows Forms GUI hangs when calling OpenFileDialog.ShowDialog()

my project a three tier architecture project talking to a WCF service in the backend. When the backend is able to fetch data from the service, it notifies the business layer using publish-subscribe, which in return notifies the GUI layer.

I have added an OpenFileDialog to my UI design using Visual Studios designer. A button event handler calls the ShowDialog message. However, once I click the button, the whole UI hangs.

Having googled around a bit, I found out that using delegates is the preferred way to handle tasks like this. However, with nor without delegate the problem persists.

Currently my code looks like this:

private void bOpen_Click(object sender, EventArgs e)
Func<Image> del = delegate
OpenFileDialog d = new OpenFileDialog();
if (d.ShowDialog() == DialogResult.OK)
return Image.FromFile(d.FileName);

return null;


I'm coming from the Java world, so I'm not really familiar with the intricacies of C# UI programming.

Anything I'm missing here?

Answer Source

I seem to have solved the problem adding the [STAThread] Attribute to the main method. I was told to do so once I ran the program in a debugger - which I hadn't done before because I ran the service from Visual Studio and the client regularly from Windows.

public static void Main(string[] args)
    GUI gui = new GUI();

Can anybody explain what exactly is going on though

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download