2013-11-01 90 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();