I am new to C# and was trying to write a form a test a network connection. The idea is that put the connection part in a thread and show a progress dialog during the connection. The following is my code:
Form_TestingConnection testingConnection = new Form_TestingConnection();
Thread t1 = new Thread(TestConnection);
try
{
testingConnection.ShowDialog();
t1.Start();
}
catch (Exception ex)
{
Logger.Error(ex);
if (MessageBox.Show(
Resources.message_connection_issue,
Resources.title_connection_issue,
MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
{
loginSuccessful = false;
}
}
TestConnection is a method to test the connection and set a static member loginSuccessful based on result. The issue I am having now is that the code stuck with testingConnection.ShowDialog(). Whenever it executes to this place, it never goes forward. Any suggestions? Thanks a lot.
ShowDialogshows the form modally. This means that the form will show, all other forms will be disabled, and theShowDialogfunction will not return until the modal dialog is closed.Use
Showinstead. This shows the form modeless. When you do that theShowfunction returns immediately and the form stays open.You can think of
ShowDialogas being synchronous andShowas being asynchronous.Make sure that any methods in the thread which need to update progress on the form are called using
InvokeorBeginInvoketo ensure that they run in the context of the main UI thread.Finally, your code as it stands does not wait until the thread has done its work. The try/catch block only wraps the form show and the beginning of the thread’s execution (
t1.Start()). When you callStarton a thread that call returns asynchronously and the thread continues to do its work. I’m not quite sure what your code is trying to do, but I suspect that thecatchblock should be inside the thread.