2015-08-28 64 views
0

这是我的代码。我使用函数来检索列表,但它没有发送它。将函数返回给函数

public List<string> country_set() 
{ 
    mCountryUrl = new Uri ("http://xxxxxxx.wwww/restservice/country"); 
    mList = new List<string>(); 
    mCountry = new List<Country>(); 
    WebClient client = new WebClient(); 
    client.DownloadDataAsync (mCountryUrl); 
    client.DownloadDataCompleted += (sender, e) => { 
     RunOnUiThread (() => { 
      string json = Encoding.UTF8.GetString (e.Result); 
      mCountry = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>> (json); 
      Console.WriteLine (mCountry.Count.ToString()); 
      int x = mCountry.Count; 
      for(int i=0; i< x ; i++) 
      { 
       mList.Add(mCountry[i].name); 
      } 
     }); 
    }; 
    return mList; 
} 

它引发异常。 请帮助我

+3

你会得到哪些例外? – Chostakovitch

+3

什么行引发异常? – bkribbs

+0

除非它是android的设计模式,否则您怀疑您返回的是带有0个元素的列表,并派发一个线程将项添加到该列表中(这也不是线程安全的)。 – Rob

回答

1

问题是,在调用Web服务器完成之前,您的方法完成后立即返回mList。现在,在您的调用代码检查列表以查找它为空之后,最终将调用服务器并完成您的列表,这已经太晚了!

这将解决这个问题:

 var mCountryUrl = new Uri("http://xxxxxxx.wwww/restservice/country"); 
     var mList = new List<string>(); 
     var mCountry = new List<Country>(); 
     WebClient client = new WebClient(); 
     var data = client.DownloadData(mCountryUrl); 

     string json = Encoding.UTF8.GetString(data); 
     mCountry = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>>(json); 
     Console.WriteLine(mCountry.Count.ToString()); 
     int x = mCountry.Count; 
     for (int i = 0; i < x; i++) 
     { 
      mList.Add(mCountry[i].name); 

     } 

     return mList; 
+0

谢谢你的帮助......它运作良好......我会永远记住这一点...... – sam

+0

不客气! – Alireza

+1

这不是异步的,因为海报的版本是(试图成为)。 –

1

这个怎么样:

public async Task<List<string>> country_set() 
{ 
    mCountryUrl = new Uri ("http://xxxxxxx.wwww/restservice/country"); 
    mList = new List<string>(); 
    mCountry = new List<Country>(); 
    WebClient client = new WebClient(); 
    byte[] data = await client.DownloadDataTaskAsync(mCountryUrl); 
    string json = Encoding.UTF8.GetString(data); 
    mCountry = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>> (json); 
    Console.WriteLine (mCountry.Count.ToString()); 
    int x = mCountry.Count; 
    for(int i=0; i<x; i++)   
     mList.Add(mCountry[i].name);   

    return mList; 
} 

它使用.NET中的新异步模式。

编辑:代码是从Android应用程序键入。任何出现语法错误(或任何其他类型)的人,请在评论中发出信号。

+0

感谢您的回复......它也在工作.... – sam