0

I do my first tries in c#. In my application a new Fom is created to show some measurements. i do this in a thread. on form closing i will exit the thread. sometimes it throws a ObjectDisposedException exception. i tried to handle it with a mutex. but then i have a dead lock.

private void FormClosing(object sender, FormClosingEventArgs e)
{
    m_mutClosing.WaitOne();
    bDoWork = false;
    m_mutClosing.ReleaseMutex();
}


    public void DoWork()
    {
        while (bDoWork)
        {
            i++;

            m_mutClosing.WaitOne();
            this.Invoke((MethodInvoker)delegate()
            {
                if(textBox != null)
                    textBox.Text = i.ToString();
            });
            m_mutClosing.ReleaseMutex();

            Thread.Sleep(500);
        }

        MessageBox.Show("end thread");
    }

the problem seems like i try to write a value to the textbox until the objects get removed.

I don´t see the solution in the other question, can please someone explain?

lalelu
  • 103
  • 9
  • It could be happening because of the Thread.Sleep(500) is occurring at FormClosing. – SteveFerg Jun 27 '15 at 17:55
  • Cold rock-hard rule: *never* block the UI thread. Guaranteed to deadlock here on the Invoke() call, it cannot complete unless the UI thread is idle. You don't need Invoke at all, BeginInvoke is fine. – Hans Passant Jun 27 '15 at 17:55
  • have you tried `Dispatcher.Invoke()` for thread? UI is in main thread so you must use `Dispatcher.Invoke(...)` to connect this threads – M.kazem Akhgary Jun 27 '15 at 17:56
  • it is my first time programming c#, can you please give me some more code? thanks a lot – lalelu Jun 27 '15 at 17:59

0 Answers0