2013-11-01 88 views
0

我在這裏問一般問題。我真的不知道該在這裏做什麼。我開發了一個帶有後端的Windows Phone 8移動應用程序作爲Web API服務的Web服務。它有大約4到5個屏幕。windows phone 8(與web api連接)問題

問題: 當我第一次加載我的應用程序,讓一切負載(未由應用程序欄要到第二個窗口或第三窗口或第四窗口和啓動另一個開斷從的WebAPI操作取提取記錄)。它工作正常。

但如果我曾經讓第一次加載運行,並去第二次獲取記錄。它會產生巨大的問題。 (延遲,返回null等)。任何想法如何在第一次抓取正在運行時用第二次抓取來克服這個問題。這是一個普遍的問題?或者只有我有這個問題?

這是我的代碼,我使用

private static readonly HttpClient client; 

    public static Uri ServerBaseUri 
    { 
     get { return new Uri("http://169.254.80.80:30134/api/"); } 
    } 

    static PhoneClient() 
    {   
     client =new HttpClient(); 
     client.MaxResponseContentBufferSize = 256000; 
     client.Timeout = TimeSpan.FromSeconds(100); 
     client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); 
    }  

    public async static Task<List<Categories>> GetDefaultCategories() 
    {  
     HttpResponseMessage getresponse = await client.GetAsync(ServerBaseUri + "Categorys");      
     string json = await getresponse.Content.ReadAsStringAsync();   
     json = json.Replace("<br>", Environment.NewLine); 
     var categories = JsonConvert.DeserializeObject<List<Categories>>(json); 
     return categories.ToList(); 
    } 
+5

你必須使用的HttpClient的新實例,爲每個請求。在你的例子中一切都是靜態的。這就是爲什麼你有兩個或更多的請求意想不到的結果。 –

回答

2

有兩個主要的問題,因爲在弗他的評論指出。您需要爲每個請求創建一個新的HttpClient實例,我也建議不要使用靜態。

public class DataService 
{ 
    public HttpClient CreateHttpClient() 
    { 
     var client = new HttpClient(); 
     client.MaxResponseContentBufferSize = 256000; 
     client.Timeout = TimeSpan.FromSeconds(100); 
     // I'm not sure why you're adding this, I wouldn't 
     client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); 
     return client; 
    } 

    public async Task<List<Categories>> GetDefaultCategories() 
    { 
     var client = CreateHttpClient(); 
     HttpResponseMessage getresponse = await client.GetAsync(ServerBaseUri + "Categorys");      
     string json = await getresponse.Content.ReadAsStringAsync();   
     json = json.Replace("<br>", Environment.NewLine); 
     var categories = JsonConvert.DeserializeObject<List<Categories>>(json); 
     return categories.ToList(); 
    } 
} 

如果你絕對必須在靜,和我不建議這個技術,但是,你可以把你的應用程序類靜態訪問該服務的實例得到它輕鬆設置並運行。我更喜歡依賴注入技術。重要的部分是你限制你的靜態實例。如果我在我的代碼中有任何東西,我傾向於將它們掛在主App類上。

public class App 
{ 
    public static DataService DataService { get; set; } 

    static App() 
    { 
    DataService = new DataService(); 
    } 
    // other app.xaml.cs stuff 
} 

然後在你的代碼的任何地方,你可以撥打:

var categories = await App.DataService.GetDefaultCategories();