引发异常:UWP后台任务中的未知模块中的“ System.TypeLoadException”

时间:2019-02-19 05:27:22

标签: c# uwp httpclient background-task

这段代码给了我一个例外

  

抛出异常:未知模块中的'System.TypeLoadException'

public sealed class SampleBackgroundTask2 : IBackgroundTask
{

        EasClientDeviceInformation currentDeviceInfo;

        BackgroundTaskCancellationReason _cancelReason = BackgroundTaskCancellationReason.Abort;

        BackgroundTaskDeferral _deferral = null;

        IBackgroundTaskInstance _taskInstance = null;

        ThreadPoolTimer _periodicTimer = null;

        //
        // The Run method is the entry point of a background task.
        //
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            currentDeviceInfo = new EasClientDeviceInformation();

            var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
            var settings = ApplicationData.Current.LocalSettings;
            settings.Values["BackgroundWorkCost2"] = cost.ToString();

            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

            _deferral = taskInstance.GetDeferral();
            _taskInstance = taskInstance;

            _periodicTimer = ThreadPoolTimer.CreateTimer(new TimerElapsedHandler(PeriodicTimerCallbackAsync), TimeSpan.FromSeconds(1));
        }

        private async void PeriodicTimerCallbackAsync(ThreadPoolTimer timer)
        {
            try
            {
                var httpClient = new HttpClient(new HttpClientHandler()); 

                string urlPath = (string)ApplicationData.Current.LocalSettings.Values["ServerIPAddress"] + "/Api/Version1/IsUpdatePersonal";

                HttpResponseMessage response = await httpClient.PostAsync(urlPath,
                    new StringContent(JsonConvert.SerializeObject(currentDeviceInfo.Id.ToString()), Encoding.UTF8, "application/json")); // new FormUrlEncodedContent(values)

                response.EnsureSuccessStatusCode();

                if (response.IsSuccessStatusCode)
                {
                    string jsonText = await response.Content.ReadAsStringAsync();
                    var customObj = JsonConvert.DeserializeObject<bool>(jsonText, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });

                    if (customObj) // Если TRUE  то да надо сообщить пользователю о необходимости обновления
                    {
                        ShowToastNotification("Ttitle", "Message");
                    }
                }
            }
            catch (HttpRequestException ex)
            {
            }
            catch (Exception ex)
            {
            }
            finally
            {
                _periodicTimer.Cancel();
                _deferral.Complete();
            }
        }

private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            _cancelReason = reason;
        }
}

如果我评论async / await和HttpClient的地方,那么也不例外。

那么我的代码有什么问题? 还是使用UWP后台任务进行异步GET / POST做得好?

我尝试了一些经典的解决方案,例如

public async void Run(IBackgroundTaskInstance taskInstance)
{
 BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
 //
 // Start one (or more) async
 // Use the await keyword
 //
 // await SomeMethodAsync();


        var uri = new System.Uri("http://www.bing.com");
        using (var httpClient = new Windows.Web.Http.HttpClient())
        {
            // Always catch network exceptions for async methods
            try
            {
                string result = await httpClient.GetStringAsync(uri);
            }
            catch (Exception ex)
            {
                // Details in ex.Message and ex.HResult.
            }
        }


 _deferral.Complete();
}

但是一旦我将HttpClient放在SomeMethodAsync()里面,它就不会解决上述错误。

此解决方案对HttpClient.GetAsync fails in background task with lock screen access and both TimeTrigger or MaintenanceTrigger

无济于事

谢谢!

1 个答案:

答案 0 :(得分:1)

我有点简化了解决方案,并删除了ThreadPoolTimer,因为我不确定为什么从代码中使用了它。请说明解决方案是否需要。

如果ThreadPoolTimer是可选的,则可以尝试以下代码:

public sealed class SampleBackgroundTask2 : IBackgroundTask
    {

        EasClientDeviceInformation currentDeviceInfo;

        BackgroundTaskCancellationReason _cancelReason = BackgroundTaskCancellationReason.Abort;

        BackgroundTaskDeferral _deferral = null;

        //
        // The Run method is the entry point of a background task.
        //
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            currentDeviceInfo = new EasClientDeviceInformation();

            var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
            var settings = ApplicationData.Current.LocalSettings;
            settings.Values["BackgroundWorkCost2"] = cost.ToString();

            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

            _deferral = taskInstance.GetDeferral();
            await asynchronousAPICall();
            _deferral.Complete(); //calling this only when the API call is complete and the toast notification is shown
        }
        private async Task asynchronousAPICall()
        {
            try
            {
                var httpClient = new HttpClient(new HttpClientHandler());

                string urlPath = (string)ApplicationData.Current.LocalSettings.Values["ServerIPAddress"] + "/Api/Version1/IsUpdatePersonal";

                HttpResponseMessage response = await httpClient.PostAsync(urlPath,
                    new StringContent(JsonConvert.SerializeObject(currentDeviceInfo.Id.ToString()), Encoding.UTF8, "application/json")); // new FormUrlEncodedContent(values)

                response.EnsureSuccessStatusCode();

                if (response.IsSuccessStatusCode)
                {
                    string jsonText = await response.Content.ReadAsStringAsync();
                    var customObj = JsonConvert.DeserializeObject<bool>(jsonText, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });

                    if (customObj) // Если TRUE  то да надо сообщить пользователю о необходимости обновления
                    {
                        ShowToastNotification("Ttitle", "Message");
                    }
                }
            }
            catch (HttpRequestException ex)
            {
            }
            catch (Exception ex)
            {
            }
            finally
            {
                _deferral.Complete();
            }
        }

        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            _cancelReason = reason;
        }
    }

请告诉我这是否适合您。