2011-09-08 52 views
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); 
............. 

回答

1

使用工作线程进行查询,使用Control.Invoke更新UI或使用异步调用从服务中获取数据。不知道更多关于你如何获得数据和做人口的信息,这些信息尽可能详细。

编辑

您在卸载的工作线程试图通过您的来电调用,这一切举动回到UI线程颠覆。你需要沿着这些线路做一些事情:

private void MyThreadProc() 
{ 
    // get the data from the web service here 

    this.Invoke(new EventHandler(delegate 
    { 
     // update your ListView here 
    })); 
} 

注意,命令的长期运行的部分将Invoke调用中包含。

+0

我尝试了工作线程,但仍然冻结了UI ...。我会发布我的所有代码,看看你的想法。 – JPM

+1

因为您使用了Invoke(),所以您的线程运行UI线程上的所有代码。您需要完全在工作线程上获取数据,然后通过Invoke()将数据传回给UI线程以填充列表。你的代码仍然阻塞UI线程。这是说,我不知道这是否会解决原来的问题 –

+0

是的,这是合理的,必须厌倦了看这个代码...呃! – JPM