简体   繁体   中英

sqlite query not working in background in winrt

I've created a winrt project. I'm using two methods one for inserting the data and other for fetching the data.I'm trying to save the data during a time trigger event. The data is not saved when I'm inserting the data in background. When I'm inserting a data using the same method on a button click event the code is working. Here is the code where I'm calling the method to insert the data:

public sealed class BackgroundTask:IBackgroundTask
    {
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            ToastTemplateType toastTemplate = ToastTemplateType.ToastText02;            
            XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);            
            XmlNodeList textElements = toastXml.GetElementsByTagName("text");            
            textElements[0].AppendChild(toastXml.CreateTextNode("Background Task"));            
            textElements[1].AppendChild(toastXml.CreateTextNode("I'm message from your background task!"));            
            Database d = new Database();
            d.saveData("new entry"); //calling the method to insert the string
            ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));
        }
    }

The 'saveData'method:

public async void saveData(string data)
        {
            SQLiteAsyncConnection connection = new SQLiteAsyncConnection("TimeDb.db");
            try
            {
                var Db = new Database() { 
                    Data = data
                };                
                await connection.InsertAsync(Db);
            }
            catch (Exception ex)
            {

            }            
        }

As the data saving is async. Get deferral should be done.

The BackGround task should do get referral at the start of the background task. The get deferral is needed to run asynchronous code.

var deferral = taskInstance.GetDeferral(); should be the first line of the run function

deferral.Complete(); should be the last line of the run function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM