Hello everyone.
Here's what I trying to do:
I have 1-100 timespan stored in a database and once sorted I take the one closest to my current.timeofday and create a task with it. Now the first part is easy, but I've been trying several solutions online to create a task but none seems to fit. Here is the closest I've been with someone else's solution:
private void CreateTask(TimeSpan alertTime)
{
DateTime current = DateTime.Now;
TimeSpan timeToGo = alertTime - current.TimeOfDay;
if (timeToGo < TimeSpan.Zero)
{
return;
}
System.Threading.Timer timer = new System.Threading.Timer(x =>
{
this.MethodToExecute()
}, null, timeToGo, Timeout.InfiniteTimeSpan);
}
Whatever action I'm trying in MethodToExecute() (such as changing content of textblock) is giving me an error "Caller thread couldn't access this object because another thread is the owner" (sorry if the translation isn't accurate).
This happens if CreateTask() is in my MainWindow or as the constructor of its own class. Any idea on how to fix that? Or a more appropriate solution?
Worth mentionning that there needs to be a task planned constantly in the background. Once one is over, another one is generated.
Thank you :)
EDIT:
This is my working MethodToExecute() content after @OriginalGriff solution:
private void MethodToExecute()
{
this.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() =>
{
this.testBox.Text = "It Works!";
}));
}
Thank you for your help ;)