1

I start new thread (worker) in userform, when this thread need something update in userform, then call Invoke method - invoke method delegate on main thread. Problem is how successfully close userform. I need first time finish worker thread, from this thread is time for time called main thread (Invoke). How in main thread wait until worker thread finish last loop.

Userform

  public partial class FormMain : Form
  {
    private bool isntSignaledStop=true;
    ...

Here is a loop method that runs on the worker thread.

private void MenuLoop()
{
  while (isntSignaledStop)
  {
    HeavyMethod();
    Invoke(DelegateWriteResultsToMenu);

    HeavyMethod2();
    Invoke(DelegateWriteResultsToMenu2);

    ...
  }
}

Main thread at end set isntSignaledStop=False. Now i need wait until worker thread is finished.

3 Answers3

1

You can use async/await approach and use tasks instead of threads. Redesign MenuLoop method to return a Task:

private volatile bool isntSignaledStop = true;
private async void ButtonStart_Click(object sender, EventArgs e)
{
    await MenuLoop();
    Close();
}

private Task MenuLoop()
{
    return Task.Run(() =>
    {
        while (isntSignaledStop)
        {
            HeavyMethod();
            Invoke(DelegateWriteResultsToMenu);

            HeavyMethod();
            Invoke(DelegateWriteResultsToMenu);
        }
    });
}
private void ButtonStop_Click(object sender, EventArgs e)
{
    isntSignaledStop = false;
}

In the UI thread you can asynchronously wait until MenuLoop finishes the work and then close the window.

AlbertK
  • 11,841
  • 5
  • 40
  • 36
0

If you have MenuLoop running on "Thread2" (pretending that's the name), I'd call Thread2.Join() on your Main Thread, which will make the main thread wait until Thread2 is finished.

I'd recommend reading this post, it's got a really great answer with 5 different ways to do this. How to wait for thread to finish with .NET?

Hopefully this helps!

Nik P
  • 116
  • 4
  • Join() lead to deadlock, because lock main thread and wait for Thread2, but he invoke method on locked main thread. –  Feb 11 '20 at 21:16
0

Thanks for the help, but I hope I found a way to do it with threads. Run main code on worker thread. Because userform itself works as I need, it allows user input, or executes invoked method from another thread, and if it does nothing, then waiting...