开发者

Multi-threading Code stuck with Form.ShowDialog() statement

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.


ShowDialog shows the form modally. This means that the form will show, all other forms will be disabled, and the ShowDialog function will not return until the modal dialog is closed.

Use Show instead. This shows the form modeless. When you do that the Show function returns immediately and the form stays open.

You can think of ShowDialog as being synchronous and Show as being asynchronous.

Make sure that any methods in the thread which need to update progress on the form are called using Invoke or BeginInvoke to 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 call Start on 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 the catch block should be inside the thread.


If you are trying to access any GUI component which belongs to a thread from another thread you should use InvokeRequired to avoid the cross thread exceptions

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜