为什么列表为空?

时间:2012-07-31 19:55:57

标签: c# observablecollection iasyncresult asynccallback

我可以从其类中访问列表( ListData ),但如果我尝试从类外部引用列表,则会将其显示为空列表。

我在getVideoList方法中将对象添加到ListData。

我添加了这段代码并且现在可以使用(轮询方法),这是不是很有效?

 IAsyncResult result = request.BeginGetResponse(new AsyncCallback(getVideoList), state);
            while (result.IsCompleted == false)
            {
               Thread.Sleep(1000);
             }

Public class otherclass{
    static void main(string [] args){
      RestProcess process = new RestProcess(videoListURI);
      process.initilaizeRest();

      foreach (VideoSeriesElement ele in process.ListData)
      {
        Console.WriteLine(ele.id);
        Console.WriteLine(ele.title);
        Console.WriteLine(ele.href);
        Console.WriteLine(ele.image);
      }

      Console.ReadLine();
  }

}

public class RestProcess
{
    /// <summary>
    /// Default constructor
    /// </summary>
    /// 
    readonly string blankimage = "http://images1.test.com/properties/NoThumbnail_HD.jpg";
    public RestProcess(string uri)
    {
        URI = uri;
        ListData = new ObservableCollection<VideoSeriesElement>();
    } 
    public ObservableCollection<VideoSeriesElement> ListData{get;set;}


    public void initilaizeRest()
    {
        WebRequest request = HttpWebRequest.Create(URI);
        request.Method = "GET";

        // RequestState is a custom class to pass info to the callback
        RequestState state = new RequestState(request, URI);
        IAsyncResult result = request.BeginGetResponse(new AsyncCallback(getVideoList), state);
    }

    public string URI{get;set;}

    /// <summary>
    /// getVideoList
    /// </summary>
    /// <param name="result"></param>
    public void getVideoList(IAsyncResult result)
    {
        RequestState state = (RequestState)result.AsyncState;
        WebRequest request = (WebRequest)state.Request;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);

        try
        {
            TextReader textreader = new StreamReader(response.GetResponseStream()); 
            XDocument doc = XDocument.Load(textreader);


            foreach(XElement videoSeriesEle in doc.Descendants("video-series"))
            {
                var videseriesEle = new VideoSeriesElement();    
                videseriesEle.id = videoSeriesEle.Attribute("id").Value;
                videseriesEle.href = videoSeriesEle.Attribute("href").Value;
                videseriesEle.title = videoSeriesEle.Element("title").Value;

                if (!videoSeriesEle.Element("images").IsEmpty && videoSeriesEle.Element("images").Elements("image") != null)
                {
                    var imagelist = videoSeriesEle.Element("images").Elements("image").ToList();
                    foreach (var ele in imagelist)
                    {
                        if (ele.Attribute("styleid").Value.Equals("5"))
                        {
                            if (videoSeriesEle.Element("images").Element("image").Attribute("href").Value != null)
                            {
                                videseriesEle.image = videoSeriesEle.Element("images").Element("image").Attribute("href").Value;
                            }

                        }
                    }

                }
                else { videseriesEle.image = blankimage; }


                //add object to list 
                ListData.Add(videseriesEle);

            }

            //Close streams 
            textreader.Close();
            response.Close();
        }
        catch (XmlException e)
        {
            Console.WriteLine(e);
        }

    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="state"></param>
    /// <param name="timedOut"></param>
    private static void ScanTimeoutCallback(object state, bool timedOut)
    {
        if (timedOut)
        {
            RequestState reqState = (RequestState)state;
            if (reqState != null)
                reqState.Request.Abort();
            Console.WriteLine("aborted- timeout");
        }
    }
}

2 个答案:

答案 0 :(得分:2)

RestProcess.initilaizeRest()方法通过IAsyncResult请求数据,这意味着获取数据的调用是异步的。在otherClass类中,您尝试在调用ListData后立即处理并遍历initilaizeRest()元素,并且很可能尚未加载数据。

要解决此问题,您应该在otherClass中有一个回调/事件处理程序,用于侦听填充数据的时间。

答案 1 :(得分:1)

您可以将IAsyncResult结果作为属性从RestProcess中的request.BeginGetResponse调用中公开,并在otherClass中阻塞,直到IAsyncResult.IsCompleted属性为true,或者使用由它公开的WaitHandle,但是您有使用的原因吗?异步BeginGetResponse调用而不是同步GetResponse调用?