Try assigning the value in this manner:
await Dispatcher.BeginInvoke( ( ) => X_Pos.Content = terms[0] );
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I have a Visual Studio C# WPF XAML application running on Windows 10 .Net 7.0.
I have an async Task that runs continuously (while (IsRuuning).
The job of the Task is to: every 100 ms, under a mutex, read the contents of a file located at statusfilePath, and use the contents of that file to update the contents of 5 Labels in the main window,
When the statement "Xpos.Contents = terms[0];" is executed, the Exception is triggered.
The Exception indicates "The calling thread cannot access this object because a different thread owns it."
How can I run a continuously running task that periodically modifies the Contents of WPF Label objects owned by the MainWindow thread?
Code for the Task:
private async Task<bool> ReadStatus()
{
System.Threading.Mutex? _mutey = null;
try
{
_mutey = System.Threading.Mutex.OpenExisting("Cinerique");
//we got Mutey and can try to obtain a lock by waitone
}
catch
{
//the specified mutex doesn't exist, we should create it
_mutey = new System.Threading.Mutex(false, "Cinerique");
}
char[] charSeparators = new char[] { ' ' };
try
{
await Task.Delay(1000);
while (IsRunning)
{
await Task.Delay(100);
string resp = "";
string? status = null;
_mutey.WaitOne();
using (StreamReader sr = new StreamReader(statusfilePath))
{
status = sr.ReadLine().Trim();
}
_mutey.ReleaseMutex();
if (status != null)
{
string[] terms = status.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (terms.Count() == 5)
{
X_Pos.Content = terms[0];
}
}
}
}
catch (Exception e)
{
Exception n = e;
return true;
}
finally
{
_mutey.ReleaseMutex();
_mutey = null;
}
return true;
}
Try assigning the value in this manner:
await Dispatcher.BeginInvoke( ( ) => X_Pos.Content = terms[0] );