0
我有一个从Web服务查询填充的列表视图。问题是,如果由于网络导致http查询速度慢或者URL错误,那么查询会冻结UI一段时间。所以我的问题是如何将它抛弃到一个侧面过程并在后台填充列表?用URL webservice查询填充ListView
这里是我如何获取数据,它通常在request.GetResponse()上坐30秒或更长。我得到了JSON并解析了这个函数,但是这个函数是支持的,并且想将它包装在某些东西中。那么我该怎么做呢?
public static String get(String url) {
StringBuilder sb = new StringBuilder();
// used on each read operation
byte[] buf = new byte[32768];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Timeout = 10000;
HttpWebResponse response;
try {
response = (HttpWebResponse)request.GetResponse();
} catch (WebException we) {
return "ERROR!"
}
Stream resStream = response.GetResponseStream();
... read from stream and parse
}
####使用工作线程############的建议
这也不起作用。
// create new thread
new Thread(new ThreadStart(myTable)).Start();
使用匿名委托的myTable方法内我认为可能是最好的方法。
private void myTable() {
if (this.InvokeRequired) {
this.Invoke(new EventHandler(delegate(object obj, EventArgs a) {
// do work here
String url = "http://someurl....";
// Set the view to show details.
listView1.View = View.Details;
// Display check boxes.
listView1.CheckBoxes = false;
// Select the item and subitems when selection is made.
listView1.FullRowSelect = true;
listView1.Items.Clear();
listView1.Columns.Clear();
listView1.Columns.Add(Resources.MainColumn0, 20, HorizontalAlignment.Left);
listView1.Columns.Add(Resources.MainColumn1a, 250, HorizontalAlignment.Left);
listView1.Columns.Add(Resources.MainColumn2, 150, HorizontalAlignment.Left);
try {
// Call the function mentioned above to get the data from the webservices....
string users = get(urlUsers);
.............
我尝试了工作线程,但仍然冻结了UI ...。我会发布我的所有代码,看看你的想法。 – JPM
因为您使用了Invoke(),所以您的线程运行UI线程上的所有代码。您需要完全在工作线程上获取数据,然后通过Invoke()将数据传回给UI线程以填充列表。你的代码仍然阻塞UI线程。这是说,我不知道这是否会解决原来的问题 –
是的,这是合理的,必须厌倦了看这个代码...呃! – JPM