views:

27

answers:

2

Hi I am working in windows 7 phone based app using silverlight. I have following methods in one of my UI classes, GameScreen.xaml. I am calling startTimer method in the constructor GameScreen. Problem is that when the updateTime method is called and

timeLabel.Text = "Time left:  00 : " + time;

line is executed, the program throws UnauthorizedAccessException on time variable.

private void startTimer()
    {
        timeThread = new Thread(new ThreadStart(startThread));
        timeThread.Start();
    }

    public void startThread()
    {
        while (timeLeft > 0)
        {
            Thread.Sleep(1000);
            updateTime();                
            if (timePassed % 10 == 0)
            {
                findNextBGResource();
                changeBackgroundScene();
            }
        }            
    }


    private void updateTime()
    {
        // update the view
        String time = timeLeft.ToString();
        if (timeLeft < 10)
        {
            time = "0" + time;
        }
        if (doUpdateTime && timeLeft >= 0)
        {
            timeLabel.Text = "Time left:  00 : " + time;
        }
    }

Can anyone please help me in this regard?

Best Regards...

+4  A: 

Basically you can't modify the UI from anything other than the dispatcher thread. Two options:

  • Use Dispatcher.BeginInvoke to execute your ui-modifying code in the dispatcher thread
  • Use DispatcherTimer instead of starting a new thread and sleeping - that way the "tick" will occur in the UI thread already.
Jon Skeet
It worked. Thanks a lot Jon... :)
Aqueel
A: 

Are you sure it's on the time variable, not on timeLabel? You can't usually edit the UI from other threads than the one that handles the UI.

greve