8

I have a form that starts a thread. Now I want the form to auto-close when this thread terminates.

The only solution I found so far is adding a timer to the form and check if thread is alive on every tick. But I want to know if there is a better way to do that?

Currently my code looks more less like this

partial class SyncForm : Form {
    Thread tr;

    public SyncForm()
    {
        InitializeComponent();
    }

    void SyncForm_Load(object sender, EventArgs e)
    {
        thread = new Thread(new ThreadStart(Synchronize));
        thread.IsBackground = true;
        thread.Start();
        threadTimer.Start();
    }

    void threadTimer_Tick(object sender, EventArgs e)
    {
        if (!thread.IsAlive)
        {
            Close();
        }
    }

    void Synchronize()
    {
        // code here
    }
}

6 Answers 6

12

The BackgroundWorker class exists for this sort of thread management to save you having to roll your own; it offers a RunWorkerCompleted event which you can just listen for.

0
6

Edit to make it call a helper method so it's cleaner.

thread = new Thread(() => { Synchronize(); OnWorkComplete(); });

...

private void OnWorkComplete()
{
    Close();
}
4
  • This doesn't work if the above methods has parameters and multiple threads. Sync(param1) takes 30 seconds, and when it executes OnWorkComplete i have paramx on the current param1 and i get wrong results :(
    – Sakthivel
    Commented Feb 13, 2014 at 15:05
  • @Sakthivel, I think your issue is related to non local parameters. you need to create a local instance of your param1 before passing it to function for example Synchronize
    – AaA
    Commented Jul 17, 2018 at 6:29
  • @Okuma.Scott, why it dosn't work? I don't have linq but I do have .NET 4 and it is working
    – AaA
    Commented Jul 17, 2018 at 6:30
  • My only issue is how to pass param from Sync to Complete
    – AaA
    Commented Jul 17, 2018 at 6:31
6

If you have a look at a BackgroundWorker, there is a RunWorkerCompleted event that is called when the worker completes.

For more info on BackgroundWorkers Click Here

Or

You could add a call to a complete function from the Thread once it has finished, and invoke it.

void Synchronize()
{
    //DoWork();
    //FinishedWork();
}

void FinishedWork()
{
if (InvokeRequired == true)
  {
  //Invoke
  }
else
  {
  //Close
  }
}
1

Have a look at delegates, IAsyncResult, BeginInvoke and AsyncCallback

1

At the end of your thread method, you can call Close() using the Invoke() method (because most WinForms methods should be called from the UI thread):

public void Synchronize()
{
   Invoke(new MethodInvoker(Close));
}
0

Solution for arbitrary thread (e.g. started by some other code), using UnmanagedThreadUtils package:

// Use static field to make sure that delegate is alive.
private static readonly UnmanagedThread.ThreadExitCallback ThreadExitCallbackDelegate = OnThreadExit;

public static void Main()
{
    var threadExitCallbackDelegatePtr = Marshal.GetFunctionPointerForDelegate(ThreadExitCallbackDelegate);
    var callbackId = UnmanagedThread.SetThreadExitCallback(threadExitCallbackDelegatePtr);

    for (var i = 1; i <= ThreadCount; i++)
    {
        var threadLocalVal = i;

        var thread = new Thread(_ =>
        {
            Console.WriteLine($"Managed thread #{threadLocalVal} started.");
            UnmanagedThread.EnableCurrentThreadExitEvent(callbackId, new IntPtr(threadLocalVal));
        });

        thread.Start();
    }

    UnmanagedThread.RemoveThreadExitCallback(callbackId);
}

private static void OnThreadExit(IntPtr data)
{
    Console.WriteLine($"Unmanaged thread #{data.ToInt64()} is exiting.");
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.