2011-09-28 39 views
1

我试过这个代码在一个正常的C#应用​​程序,它工作正常。在monodroid中,当我尝试以任何方式从流(或基本流)读取时,它完全错误(换句话说,甚至没有尝试捕获工作)。请帮助:Monodroid WebRequest炸弹应用程序

try 
{ 
    WebRequest request = WebRequest.Create(string.Format("http://maps.google.com/maps/geo?q={0},{1}&output=xml&sensor=false", "35.245619","-98.276369")); 
    WebResponse wresponse = request.GetResponse(); 

    using (StreamReader sr = new StreamReader(wresponse.GetResponseStream())) 
    { 
     RunOnUiThread(() => _debug.Text = (sr.ReadToEnd()).ToString()); 
    } 
    wresponse.Close(); 
} 
catch (Exception ex) 
{ 
    RunOnUiThread(() => _debug.Text = string.Format("Exception: ", ex.Message)); 
} 

_debug是我的UI一个TextView对象。

回答

1

这种方式怎么样?

try 
{ 
    WebRequest request = WebRequest.Create(string.Format("http://maps.google.com/maps/geo?q={0},{1}&output=xml&sensor=false", "35.245619","-98.276369")); 
    WebResponse wresponse = request.GetResponse(); 
    var resp=string.Empty; 
    using (StreamReader sr = new StreamReader(wresponse.GetResponseStream())) 
    { 
     resp=sr.ReadToEnd().ToString(); 
    } 
    wresponse.Close(); 
    RunOnUiThread(() => _debug.Text = resp); 
} 
catch (Exception ex) 
{ 
    RunOnUiThread(() => _debug.Text = string.Format("Exception: ", ex.Message)); 
} 
1

声音提供了答案。这应该工作。我只是解释一下原因。

从你的代码看来,你似乎正在后台线程上执行HTTP请求。这就是为什么你需要执行RunOnUiThread。这是一个非常好的方法。

但是,RunOnUiThread并不保证代码将立即在UI线程上执行。它只是向UI线程运行循环发布消息。当UI线程有机会时,它会执行它。

这意味着“wresponse.close()”可能会在“resp = sr.ReadToEnd()。ToString()”之前运行。由于响应已关闭,因此尝试从中读取将导致错误。但错误发生在UI线程上,因为读取尝试将在UI线程上进行。这就是为什么你的try/catch块不起作用。

在Sound的代码中,这个问题被消除了。值得一提的是,由于实际读取的字节被卸载到工作线程,因此这段代码的性能也会更好,因此您的UI线程将更具响应能力。