2012-03-04 3 views
0

30 초 동안 사용하지 않는 WPF 응용 프로그램의 기본 메뉴로 돌아가는 타이머를 만들려고합니다. 하지만 "다른 스레드가 소유하고 있기 때문에 호출하는 스레드가이 개체에 액세스 할 수 없습니다."라는 오류 메시지가 나타납니다. FadeOut()에서 발생합니다. storyboard.Begin(uc);호출 스레드가이 객체에 액세스 할 수 없습니다.

발송자를 호출하는 것과 관련된 몇 가지 해결책을 보았지만 제 경우에는 적용하는 방법을 모르겠습니다.

this.Dispatcher.Invoke((Action)(()=>{ 
     // In here, try to call the stuff which making some changes on the UI 
}); 

예를 들면 : :

public void ResetScreen() 
{ 
    if (!mainScreen) 
    { 
     Timer myTimer = new Timer(); 
     myTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
     myTimer.Interval = 1000; 
     myTimer.Start(); 
    } 
} 

private void OnTimedEvent(object source, ElapsedEventArgs e) 
{ 
    TransitionContent(oldScreen, newScreen); 
} 

private void FadeIn(FrameworkElement uc) 
{ 
    DoubleAnimation dAnimation = new DoubleAnimation(); 
    dAnimation.Duration = new Duration(TimeSpan.FromSeconds(1.0)); 
    dAnimation.From = 0; 
    dAnimation.To = 1; 
    Storyboard.SetTarget(dAnimation, uc); 
    Storyboard.SetTargetProperty(dAnimation, new PropertyPath(OpacityProperty)); 
    Storyboard storyboard = new Storyboard(); 
    storyboard.Children.Add(dAnimation); 
    storyboard.Begin(uc); 
} 

private void FadeOut(FrameworkElement uc) 
{ 
    DoubleAnimation dAnimation = new DoubleAnimation(); 
    dAnimation.Duration = new Duration(TimeSpan.FromSeconds(1.0)); 
    dAnimation.From = 1; 
    dAnimation.To = 0; 
    Storyboard.SetTarget(dAnimation, uc); 
    Storyboard.SetTargetProperty(dAnimation, new PropertyPath(OpacityProperty)); 
    Storyboard storyboard = new Storyboard(); 
    storyboard.Children.Add(dAnimation); 
    storyboard.Begin(uc); 
} 

private void TransitionContent(FrameworkElement oldScreen, FrameworkElement newScreen) 
{ 
    FadeOut(oldScreen); 
    FadeIn(newScreen); 
} 

답변

2

이것은 하나의 해결책이 될 수

private void TransitionContent(FrameworkElement oldScreen, FrameworkElement newScreen) 
{ 
    this.Dispatcher.Invoke((Action)(()=>{ 
      FadeOut(oldScreen); 
      FadeIn(newScreen); 
    }); 
} 
+0

이 솔루션은 효과가 있습니다. 감사합니다. – Michael

1

귀하의 문제는 System.Timers.Timer 이벤트가 UI와 다른 스레드에서 실행한다는 것입니다 실. 다른 사람들이 언급 한대로 직접 호출하거나 DispatcherTimer을 사용할 수 있습니다.

관련 문제