Click here to Skip to main content
15,887,776 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:

C#
private void CreateTask(TimeSpan alertTime)
{
            DateTime current = DateTime.Now;
            TimeSpan timeToGo = alertTime - current.TimeOfDay;
            if (timeToGo < TimeSpan.Zero)
            {
                return;//time already passed
            }
            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:

C#
private void MethodToExecute()
{
    this.Dispatcher.BeginInvoke(
    DispatcherPriority.Background,
    new Action(() =>
    {
        this.testBox.Text = "It Works!";
    }));
}


Thank you for your help ;)
Posted
Updated 8-Aug-15 2:31am
v3

1 solution

You can only access UI controls from the thread they are created on: for all other threads you need to Invoke. And the Timer event is happening on a different thread.

So invoke it. For WPF, that means the Dispatcher: Dispatcher.CheckAccess[^] - the link includes an example.
 
Share this answer
 
Comments
[no name] 8-Aug-15 7:53am    
"And the Timer event is happenintg on a different thread":
Sure? I never had such a problem while using "Timer" and write something to a say LogListbox. But I'm ready to learn.

[Edit]
Just recognized, of course it depends on which thread creates the timer. Sorry.
OriginalGriff 8-Aug-15 8:03am    
No problem!
It was the "Caller thread couldn't access this object because another thread is the owner" that gives it away.
S_Augure 8-Aug-15 8:32am    
Updated the question, thank you for your help :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900