0

I have the code below (but doesn't work) .. i need to wait till the thread complete its job then execute then next command

private void btnPaste_Click(object sender, EventArgs e)
    {
        if (copiedItems != null)
        {
            if (copy)
            {
                System.Threading.Thread thPASTE = new System.Threading.Thread(PasteFromCopy);
                thPASTE.Start(currAddress);
                lock (this)
                {
                    btnRefresh_Click(sender, e);
                }
            }
            else
            {
                System.Threading.Thread thPASTE = new System.Threading.Thread(PasteFromMove);
                thPASTE.Start(currAddress);
                lock (this)
                {
                    btnRefresh_Click(sender, e);
                }
            }
        }
    }

the paste should do some code then after that i should refresh the list im showing.. i need to do it this way, because it doesn't work for me when i call the refresh in the thread
how do i do it ??

Murhaf Sousli
  • 12,622
  • 20
  • 119
  • 185
  • You may also want to consider a private locking variable, instead of taking a lock on `this`. e.g., `private readonly object lockObject = new object();` You can see this thread for more details http://stackoverflow.com/questions/251391/why-is-lockthis-bad – Bryan Crosby Feb 07 '12 at 22:36
  • There's no point in starting a thread and then wait for it. You might as well directly call PasteFromCopy() – Hans Passant Feb 08 '12 at 01:31

3 Answers3

5

You could use the Join method on the thread instance which will block the calling thread until the other thread has finished.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

You can also use WaitHandles and use the WaitOne or WaitAll methods.

Brad Semrad
  • 1,501
  • 1
  • 11
  • 19
1

i need to do it this way, because it doesn't work for me when i call the refresh in the thread

Your problem is not related with thread synchronizations like Join, Wait , WaitOne etc.

Updating user interface elements from a secondary thread in Windows Forms is tricky because a secondary thread is not allowed to read or write property values directly from a form or any of its child controls. This restriction exists because form objects and control objects in Windows Forms are not thread-safe. The only thread that's allowed to directly access a property value of a form or one of its controls is the primary UI thread

To update your GUI from a thread (other your main thread), you need to call Invoke or BeginInvoke methods of your form(or some controls) to insert delegates into the Dispatcher of the UI thread.

These links can help you.

How to update GUI from another thread in C#?

Updating the UI from a Secondary Thread

Updating the GUI from another thread made easy

Community
  • 1
  • 1
L.B
  • 114,136
  • 19
  • 178
  • 224