Ich entwickle eine kleine Software zum Abrufen von Daten vom Gerät und senden Sie es an den Server. Da es eine Desktop-Software ist, so muss ich aktuelle verfügbare Nachricht zur GUI hinzufügen. Es funktioniert gut, bis ich diesen Thread beigetreten bin. Wenn ich versuche, diesen Thread zu stoppen, indem ich den Flag-Wert (derzeit IsRunning ist mein Flag) auf false setze und dann versuche, Gui eine Nachricht hinzuzufügen, friere ich die ganze Anwendung ein. Wahrscheinlich ein Deadlock-Problem, aber ich bin mir nicht ganz sicher. Bitte helfenVerwendung von Invoke zum Vermeiden von Cross Thread-Operationen?
Anschlagpunkt des Gewindes
try
{
IsRunning = false;
_bgThread.Join(); //this makes a deadlock probably
//_bgThread.Join(7000); //this works fine
}
catch (ThreadStartException ese)
{
throw ese;
}
// Thema Methode
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
}
// Delegatmethode
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);
}
}