I create a thread within the main form load event of the application and initialize it with a method then start this thread and there is no problem till this point the problem is that when I click on any button on the main form to open another form lets say the sales invoice form it does not open until the code within the method running within the created thread finish its task then the sales invoice form opens.

I'm wondering how threading makes such problem

Does any one of you have an idead about what may be the problem?

Without seeing your code it's a bit difficult, but there are some general rules you will need to be aware of when running in a multi-threaded environment. For example, you will need to exert caution when sharing data between threads. Is the callback to your button click waiting for a variable or object that is instantiated by the other thread?

If have a ManualResetEvent and you can initialize that to false (not signaled state). Then in the thread that opens the other form you can waitone() .
Once all the statements in the first thread is done you can signal the state by setting ManualResetEvent to true, at this point of time the statements after waitone() would execute (in ur case opening of the other form).

Refer The following For ManualResetEvent and Waitone()

Thanks guys

The Code looks like this:

private void myMethod()
{
    // execution of some sql statements goes here within this method
}


private void MainForm_Load(object sender, EventArgs e)
{
    // some code

    System.Threading.Thread newThread = new System.Threading.Thread(System.Threading.ThreadStart(myMethod));
    newThread.Start();

    // some code
}

private void Button_Click(object sender, EventArgs e)
{
    SalesInvoiceWindow sales = new SalesInvoiceWindow();
    sales.Show();
}

The problem is that when click on the button the code within the click event does not execute unless the code within myMethod finishes it work!!!!!

I could be wrong here, but I don't think the MainForm will accept events such as button clicks until it is finished loading, ie until the Load event completes. Have you tried stepping through your code in the debugger to determine when the Load event completes? Maybe something else in the "some code" section(s) are causing the delay.

Have you looked at a BackgroundWorker to do what you are after instead? I prefer to encapsulate threads that I want to run asynchronously in a BackgroundWorker rather than trying to execute my own threads.

This article has been dead for over six months. Start a new discussion instead.