0

I am developing a small software for retrieving data from device and send it to server.As it is a desktop software so i have to add current available message to GUI.It works fine until i have joined those Thread. When i try to stop this thread by setting flag(currently IsRunning is my flag) value to false and then try to add a message to Gui it freeze whole application.probably deadlock issue but i am not entirely sure about that. Please help

stop point of thread

try
        {
            IsRunning = false;
           _bgThread.Join(); //this makes a deadlock probably

           //_bgThread.Join(7000); //this works fine 
        }
        catch (ThreadStartException ese)
        {
            throw ese;
        }

//Thread method

private void DeviceSync()
    {
        while (IsRunning)
        {
            // ...statement
        }
    //now what actually happen in my case is 
    //when i try to stop the thread by setting the value of "IsRunning" false
    //it comes to this line and pass a message to UI by throwing OnThrowingMessage event

        var info = "Service Stopped at: " + DateTime.Now.ToString(BusinessRules.DateTimeFormat);
        OnThrowingMessage(info, MessageType.Important);// this event fails to bind message to UI thread causes freeze UI
    }

//delegate method

 private void OnGuiMessaging(string message, MessageType messageType)
    {
        try
        {
    //for avoiding Invalid Cross-thread Operations as sometimes it is calling from background thread
            if (this.currentStatedataGridView.InvokeRequired)
            {
                Console.WriteLine("Here it is for the first time ");
               //Application freeze here 
                this.currentStatedataGridView.Invoke(new SomeDelgate(OnGuiMessaging), new object[] { message, messageType });
            }
            else
            {
               //add row
                string[] rowData = new string[] { DateTime.Now.ToString(BusinessRules.DateTimeFormat), message };
                currentStatedataGridView.Rows.Insert(0, rowData);
                currentStatedataGridView.Rows[0].DefaultCellStyle.BackColor = rowColor;
             }
       }
        catch (Exception ex)
        {
            Log.Error(ex);
        }
    }

1 Answers1

0

fixed this issue :)

Replace Delegate.Invoke with Delegate.BeginInvoke solve my issue because it executes asynchronously as it Executes on the UI thread, and calling thread doesn't wait for completion. on the other side Control.Invoke Executes on the UI thread, but calling thread waits for completion before continuing.

can see more from What's the difference between Invoke() and BeginInvoke()

Community
  • 1
  • 1