时间触发器中的Web服务后台任务在UWP中不起作用?

时间:2016-06-10 10:21:58

标签: c# web-services restsharp windows-10-universal

我目前正在处理Windows 10后台任务,我正在将用户位置存储在我的数据库中并使用时间触发器,我正在尝试使用REST Webservice将存储的数据发送到服务器,我正在使用 RestSharp.Portable API来做到这一点。现在,问题在于,当我从后台任务调用Web服务时,请求不会发送到服务器,但是当我在前台(在我的Windows 10项目中)执行相同操作时,它可以正常工作。有人可以建议我做错了吗?

**我的TimeTrigger任务

namespace TimerTask
{
public sealed class TimeTriggerTask : IBackgroundTask
{
    private ApplicationDataContainer userSettings = ApplicationData.Current.LocalSettings;

    public async void Run(IBackgroundTaskInstance taskInstance)
    {
        DatabaseManager dbManager = new DatabaseManager();
        var location_records = dbManager.getLocationDetails();
        if (MCSManager.Instance.currentClientData == null)
        {
            ResourceContext resourceContext = ResourceContext.GetForViewIndependentUse();
            ResourceMap resourceMap = MCSExtensions.getResourceMap();
            MCSManager.Instance.currentClientData = await new JsonDataHandler().LoadJsonFileforBackgroundTask(resourceMap.GetValue("CLIENT_JSON_FILENAME",resourceContext).ValueAsString, typeof(ClientData)) as ClientData;
        }
        if (location_records !=null && location_records.Count>0)
        {
            Dictionary<string, object> contentDictionary = new Dictionary<string, object>();
            contentDictionary.Add("P_LOC_DATA", location_records);
            contentDictionary.Add("P_LAST_LOC_LAT",location_records[location_records.Count-1].LATITUDE);
            contentDictionary.Add("P_LAST_LOC_LNG", location_records[location_records.Count - 1].LONGITUDE);
            contentDictionary.Add("P_LAST_LOC_UPDATE", location_records[location_records.Count - 1].DATE_TIME);
            IRestResponse locationTrackingResponse = await new WebServiceUtility().CommonWebservice(new RequestDataGenerator().generateRequestDataForLocationTracking(contentDictionary));

            if (locationTrackingResponse.IsSuccess==true && locationTrackingResponse.RawBytes.Length>0)
            {
                byte[] decryptedbytes = WebserviceED.finaldecryptedresponse(locationTrackingResponse.RawBytes);
                string responsejson = Encoding.UTF8.GetString(decryptedbytes, 0, decryptedbytes.Length);
                JObject userInfo = JObject.Parse(responsejson);
                string result = (string)userInfo["P_RESULT"];
                if(result !=null && result.Equals("1"))
                {
                    dbManager.TruncateAllLocationTrackingData();
                    Debug.WriteLine("Data deleted successfully");
                }

            }
        }

        // simple example with a Toast, to enable this go to manifest file
        // and mark App as TastCapable - it won't work without this
        // The Task will start but there will be no Toast.
        /*ToastTemplateType toastTemplate = ToastTemplateType.ToastText02;
        XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
        XmlNodeList textElements = toastXml.GetElementsByTagName("text");
        textElements[0].AppendChild(toastXml.CreateTextNode("My first Task - Yeah"));
        textElements[1].AppendChild(toastXml.CreateTextNode("I'm a message from your background task!"));
        ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));*/
    }
}

}

我的网络服务电话     public async Task CommonWebservice(string encryptedstring)         {             ResourceContext resourceContext = ResourceContext.GetForViewIndependentUse();             ResourceMap resourceMap = MCSExtensions.getResourceMap();

        var client = new RestClient(BaseUrl + resourceMap.GetValue("WEB_SERVICE_NAME",resourceContext).ValueAsString);

        RestRequest request = new RestRequest(HttpMethod.Post);

        byte[] encryptedbytes = System.Text.Encoding.UTF8.GetBytes(encryptedstring);
        request.AddParameter("", encryptedbytes, ParameterType.RequestBody);

        var response = await client.Execute(request);

        return response;
    }

我已经在我的应用程序中注册了Background任务。另外,我建议在使用async和await时添加 Deferral

1 个答案:

答案 0 :(得分:2)

请求未正确执行,后台任务在处理请求之前被终止。

将以下代码添加到任务的开头

//get deferral to make the call awaitable BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();

以及以下代码到底

//Complete the task _deferral.Complete();

您始终可以调试后台任务以确保其正常运行。