0

RSS 리더를 구축 중이며 새 피드 항목을 확인할 주기적 작업을 추가하고 싶습니다. 새 항목을 찾으면 그에 따라 앱의 라이브 타일을 업데이트합니다.배경 에이전트에서 잘못된 스레드 간 액세스가 발생했습니다.

내가 겪는 문제는 DownloadStringAsync() 메서드를 사용하여 피드를 다운로드하고 새 항목이 들어 있는지 확인하는 것입니다. 따라서 다운로드 프로세스가 20 초 (작업을 완료하기 위해 정기적 인 작업이 주어진 시간)보다 오래 걸리는 경우가 있습니다.

필자가 원하는 것은 20 초간의 작업 후에 에이전트가 OS에 의해 종료되기 전에 NotifyComplete() 메서드가 호출되도록하는 것입니다. 이러한 이유로 15 초 간격으로 디스패처 타이머를 등록하려고합니다.이 타이머는 해당 틱 이벤트에서 NotifyComplete() 메서드를 호출합니다.

그러나 디스패처 타이머를 선언하고 사용하려고 시도했는데 잘못된 스레드 간 액세스 오류가 발생했습니다. 내 정기적 인 작업 코드에는 다음이 포함됩니다.

public class ScheduledAgent : ScheduledTaskAgent 
{ 
    //Register a DispatcherTimer 
    DispatcherTimer masterTimer = new DispatcherTimer(); 

    private static volatile bool _classInitialized; 

    public ScheduledAgent() 
    { 
     if (!_classInitialized) 
     { 
      _classInitialized = true; 
      // Subscribe to the managed exception handler 
      Deployment.Current.Dispatcher.BeginInvoke(delegate 
      { 
       Application.Current.UnhandledException += ScheduledAgent_UnhandledException; 
      }); 
     } 

     //Set Timer properties 
     masterTimer.Interval = TimeSpan.FromSeconds(15); 
     masterTimer.Tick += masterTimer_Tick; 
    } 

    protected override void OnInvoke(ScheduledTask task) 
    { 
     //TODO: Add code to perform your task in background 
     masterTimer.Start(); 

     //Call DownloadStringAsync() and perform other tasks... 
     //Call NotifyComplete() after the download is complete. 
     // 
    } 


    private void masterTimer_Tick(object sender, EventArgs e) 
    { 
     masterTimer.Stop(); 
     //There is no more time left, we must call NotifyComplete() so as to avoid 
     //having the periodic task terminated by the OS 
     NotifyComplete(); 
    } 
} 

질문의 원인은 무엇이며 문제를 해결할 수있는 방법입니다. 미리 감사드립니다.

+0

크로스 스레드 문제 :

는 코드의 모양은 제어

에 존재하는 호출 메소드를 사용하여 전달하려면 'to'NotifyComplete()'? 일찍? 당신의'ScheduledTaskAgent'가 미래에 호출 될 것이라는 것을 보장하지 않습니다 - 에이전트와 사용자가 앱을 계속 사용하면서 예외는 없습니다. –

+0

타이머 (DispatcherTimer 또는 일반 타이머)가 필요하지 않습니다. 백그라운드 에이전트의 시간 제한은 코드 실행 시간 (즉, 코드에서 사용하는 시스템 사이클의 양)에 있습니다. 서비스가 응답하기를 기다리는 시간은이 시간에 포함되지 않습니다. –

+0

@ShawnKendrot 매우 흥미로운 정보입니다. 그것을 백업 할 소스가 있습니까? –

답변

0

컨트롤을 만든 스레드가 아닌 스레드에서 UI 속성을 변경하려고하면 크로스 스레드 액세스 오류가 발생합니다. 왜 당신은`DispatcherTimer를 사용하려고 따로

Control.Invoke((MethodInvoker)delegate{ 
//Do your work here for example NotifyComplete(); 
});