Question

I have some SQL code with local database in my App, it works:

using(var ctx = new TestCTX()){
     var res = ctx.Test.ToList();
}

Then I want to use it in PeriodicTask in OnInvoke method, I get UnauthorizedAccessException:

public override void OnInvoke(ScheduledTask){
    using(var ctx = new TestCTX()){
        var res = ctx.Test.ToList();
    }
}

But then I wrap it to:

public override void OnInvoke(ScheduledTask task){
    Deployment.Current.Dispatcher.BeginInvoke(()=>{     
         using(var ctx = new TestCTX()){
             var res = ctx.Test.ToList();
         }
    });   
}

Then it works. So here is the question: Why must I wrap it into BeginInvoke ?

Was it helpful?

Solution

In WPF, only the thread that created a DispatcherObject may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a Button that was created on the UI thread. In order for the background thread to access the Content property of the Button, the background thread must delegate the work to the Dispatcher associated with the UI thread. This is accomplished by using either Invoke or BeginInvoke. Invoke is synchronous and BeginInvoke is asynchronous. The operation is added to the event queue of the Dispatcher at the specified DispatcherPriority.

BeginInvoke is asynchronous;therefore, control returns immediately to the calling object after it is called.

Invoke is a synchronous operation; therefore, control will not return to the calling object until after the callback returns.

You can read more from the below MSDN reference. MSDN reference

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top