WebApi未从Windows 10 App BackgroundTask调用

时间:2016-01-18 16:38:46

标签: c# windows-10 background-task

当我的代码转到下面的代码行

时,需要一些帮助

var result = await _httpClient.GetAsync(BASE_URI);

它被绞死,可能的原因可能是什么。这实际上是WebApi调用,系统在从BackgroundTask调用它时被挂起。有什么想法吗? 以下是完整的代码。

namespace POSBackgroundTasks
{

    public sealed class LoadDataTask : IBackgroundTask

    {

        static List<Product> Products;

        public void Run(IBackgroundTaskInstance taskInstance)

        {

            BackgroundTaskDeferral deferal = taskInstance.GetDeferral();         
            FillProducts();
            deferal.Complete();
        }

        async void FillProducts()
        {

            string BASE_URI = "https://dposapi.azurewebsites.net/DPosApi/v1/Configurations/";
            HttpClient _httpClient;
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
            BASE_URI = BASE_URI + "GetAll";
            var result = await _httpClient.GetAsync(BASE_URI);
            var productsJson = await result.Content.ReadAsStringAsync();            
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您的FillProducts方法应如下所示:

async void FillProducts()
{
    string BASE_URI = "https://dposapi.azurewebsites.net/DPosApi/v1/Configurations/";
    using (HttpClient httpClient = new HttpClient(BASE_URI))
    {
        httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
        var result = await _httpClient.GetAsync("GetAll");
        var productsJson = await result.Content.ReadAsStringAsync();            
    }
}

您需要将基本网址传递给HttpClient的构造函数,并将操作名称传递给GetAsync参数。如果这种情况持续存在,则问题出在Web服务的最后,而不是您的代码。另请注意使用using语句来处置HttpClient