我最近开始使用Xamarin而且我对c#很新。我想创建一个异步HTTP请求,所以我开始使用async和await与HttpWebRequest。但我没有得到异步调用,UI正在被阻止。这是我测试的代码。我有两个实现,RequestCitas()应该是异步的,SRequestCitas()是同步的,有什么问题?。
namespace mc
{
[Activity (Label = "mc", MainLauncher = true, Theme="@android:style/Theme.Holo.Light")]
public class MainActivity : Activity
{
List<Cita> citas;
CitaAdapter adapter;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
SetContentView (Resource.Layout.Main);
citas = new List<Cita> ();
adapter = new CitaAdapter (this, citas);
ListView listView = FindViewById<ListView> (Resource.Id.main_citas);
listView.Adapter = adapter;
var c1 = new Cita (0, "ernesto", "De los Santos", "19/2/14", "19/2/14", "09:28", "10:45");
var c2 = new Cita (1, "ernesto", "De los Santos", "19/2/14", "19/2/14", "09:28", "10:45");
var c3 = new Cita (2, "ernesto", "De los Santos", "19/2/14", "19/2/14", "09:28", "10:45");
var c4 = new Cita (3, "ernesto", "De los Santos", "19/2/14", "19/2/14", "09:28", "10:45");
var c5 = new Cita (4, "ernesto", "De los Santos", "19/2/14", "19/2/14", "09:28", "10:45");
citas.Add (c1);
citas.Add (c2);
citas.Add (c3);
citas.Add (c4);
citas.Add (c5);
Console.WriteLine ("Notificando al adaptador");
adapter.NotifyDataSetChanged ();
string result;
FindViewById<Button> (Resource.Id.button1).Click += async (sender, e) => {
result = await RequestCitas ();
};
FindViewById<Button> (Resource.Id.button2).Click += delegate {
result = SRequestCitas ();
};
}
private async Task<string> RequestCitas ()
{
// var url = "http://192.168.1.126:8081";
var url = "http://192.168.1.124";
//var method = "/citas/get";
var method = "";
var encoding = new UTF8Encoding ();
byte[] parametros = encoding.GetBytes ("usersID=97");
var request = (HttpWebRequest)WebRequest.Create (url + method);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = parametros.Length;
var dataStream = request.GetRequestStream ();
dataStream.Write (parametros, 0, parametros.Length);
dataStream.Close ();
string str = "";
Task<WebResponse> task = request.GetResponseAsync ();
WebResponse newResponse = await task;
var responseStream = newResponse.GetResponseStream ();
var streamReader = new StreamReader (responseStream, System.Text.Encoding.GetEncoding ("utf-8"));
char[] read = new Char[256];
int count = streamReader.Read (read, 0, 256);
while (count > 0) {
str += new string (read, 0, count);
count = streamReader.Read (read, 0, 256);
}
responseStream.Close ();
return str;
}
private string SRequestCitas ()
{
var url = "http://192.168.1.126:8081";
var method = "/citas/get";
var encoding = new UTF8Encoding ();
byte[] parametros = encoding.GetBytes ("usersID=97");
var request = (HttpWebRequest)WebRequest.Create (url + method);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = parametros.Length;
var dataStream = request.GetRequestStream ();
dataStream.Write (parametros, 0, parametros.Length);
dataStream.Close ();
string str = "";
HttpWebResponse newResponse = (HttpWebResponse)request.GetResponse ();
var responseStream = newResponse.GetResponseStream ();
var streamReader = new StreamReader (responseStream, System.Text.Encoding.GetEncoding ("utf-8"));
char[] read = new Char[256];
int count = streamReader.Read (read, 0, 256);
while (count > 0) {
str += new string (read, 0, count);
count = streamReader.Read (read, 0, 256);
}
responseStream.Close ();
return str;
}
}
}
答案 0 :(得分:0)
您正在使用async
方法获得响应,但您正在使用同步流操作读取流。请尝试使用streamReader.ReadAsync
。
或者,如果您感到雄心勃勃,可以尝试完全替换整个while
循环并使用:
var str = await streamReader.ReadToEndAsync();
在旁注上,StreamReader
实施了IDisposable
,并且当您完成该实例时,您并没有正确处理该实例。你可能会泄漏原生资源。
答案 1 :(得分:0)
当您创建使用await
关键字的方法时,必须将我标记为async
,以便编译器允许使用关键字。此外,您应该遵循指南并使用异步前缀
您的async
方法正在从导致您的UI阻止的StreamReader
中同步读取。
这是使用HttpClient
的异步实现:
private async Task<string> RequestCitasAsync()
{
var url = "http://192.168.1.126:8081/citas/get";
byte[] parametros = Encoding.UTF8.GetBytes("usersID=97");
var httpClient = new HttpClient();
var response = await httpClient.PostAsync(url, new ByteArrayContent(parametros));
return await response.Content.ReadAsStringAsync();
}