How to wait for a thread to finish execution in C#?
Asked Answered
Y

1

2

I have a function that is called in rapid succession that has a open database connection. my issue is that before one database connection is closed, another instance of the function is called and i could possibly receive a deadlock in the database.

I have tried:

private static WaitHandle[] waitHandles = new WaitHandle[]
    {
        new AutoResetEvent(false)
    };

protected override void Broadcast(Data data, string updatedBy)
    {
        Action newAction = new Action(() =>
        {
        DataManagerFactory.PerformWithDataManager( 
            dataManager =>
            {
                // Update status and broadcast the changes
                data.UpdateModifiedColumns(dataManager, updatedBy);

                BroadcastManager.Instance().PerformBroadcast(
                    data,
                    BroadcastAction.Update,
                    Feature.None);
            },
            e => m_log.Error(ServerLog.ConfigIdlingRequestHandler_UpdateFailed() + e.Message));
            }
        );

        Thread workerThread = new Thread(new ThreadStart(newAction));
        ThreadPool.QueueUserWorkItem(workerThread.Start, waitHandles[0]);
        WaitHandle.WaitAll(waitHandles);
    }

but i recieve a thread error and the program freezes. It has something to do with the thread start function having no parameters i believe.

Thanks for any help

Yesteryear answered 5/11, 2012 at 23:10 Comment(3)
The second object in QueueUserWorkItem is the parameter. See MSDNHoi
Usually you don't queue the Start method of a new thread on the ThreadPool. That sort of defeats the purpose. Just queue newAction. You should probably lock what ever method on your side (PerformBroadcast ?) that could result in a deadlock on the server side.Sewing
ThreadPool.QueueUserWorkItem(newAction, null); doesnt work. ThreadPool.QueueUserWorkItem(newAction, waitHandles[0]); doesnt work.Yesteryear
C
0

This is how it's done. Create class that does the job:

public class MyAsyncClass
{

    public delegate void NotifyComplete(string message);
    public event NotifyComplete NotifyCompleteEvent;

    //Starts async thread...
    public void Start()
    {
        System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(DoSomeJob));
        t.Start();
    }

    void DoSomeJob()
    {
        //just wait 5 sec for nothing special...
        System.Threading.Thread.Sleep(5000);
        if (NotifyCompleteEvent != null)
        {
            NotifyCompleteEvent("My job is completed!");
        }
    }
}

Now this is code from another class, that calls first one:

 MyAsyncClass myClass = null;


    private void button2_Click(object sender, EventArgs e)
    {
        myClass = new MyAsyncClass();
        myClass.NotifyCompleteEvent += new MyAsyncClass.NotifyComplete(myClass_NotifyCompleteEvent);
        //here I start the job inside working class...
        myClass.Start();
    }

    //here my class is notified from working class when job is completed...
    delegate void myClassDelegate(string message);
    void myClass_NotifyCompleteEvent(string message)
    {
        if (this.InvokeRequired)
        {
            Delegate d = new myClassDelegate(myClass_NotifyCompleteEvent);
            this.Invoke(d, new object[] { message });
        }
        else
        {
            MessageBox.Show(message);
        }
    }

Let me know if I need to explain some details.

Alternative to this is BackgroudWorker:

Choe answered 5/11, 2012 at 23:27 Comment(4)
i just to wait for the thread to end. i dont want to have a custom class and i dont want to use the Action Fired method of waiting. Have any tips on just waiting on a thread? i have no action i need doing after, i just need to halt execution of the father thread until the child thread is done so that no more child threads can execute said code. locking the code block doesnt work with a public static read only variable as wellYesteryear
Well closest to this is background worker. But you will have to write a few lines. Check this link for more details: msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspxChoe
that also wont work, as in my action i need custom data no available in the event argsYesteryear
As I understand your situation you should not have any problem using any of this solutions. If wait should be done on UI just disable required part on form. If wait should be done inside the code put private parameter inside your class. Something like bool WorkingInProgress. When job starts set WorkingInProgress=true. Hold (using while) any other processes until NotifyCompleteEvent delivers event. Then set WorkingInProgress=false, and continue with next thread in line.Choe

© 2022 - 2024 — McMap. All rights reserved.