开发者

WP7 WebClient DownloadStringAsync and Map

I'm using WebClient object in to poll some data from server. It's working good and it's updating text block fine. Till I don't use map on same Page. When I add a map, only one request get completed and data is retrieved only once. This is the code for getting messages:

    public MessagesPage()
    {
        InitializeComponent();
        new System.Threading.Timer(messagePolling, null, 0, 5000);   // every 5 seconds
    }

    void messagePolling(object state)
    {
        getMessages(Const.GET_MESSAGES_URL + uuid);
    }

    private void getMessages(string uri)
    {
        WebClient webClient = new WebClient();
        webClient.DownloadStringAsync(new Uri(uri));
        webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(messagesResponseCompleted);
    }

    void messagesResponseCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        lock (this)
        {
            try
            {
                string s = e.Result;
                if (s.Length > 0)
                {
                    List<Message> messagesResult = JSONHelper.Deserialize<List<Message>>(s);
                    foreach开发者_StackOverflow (Message m in messagesResult)
                    {
                        tbMessages.Text += m.message + "\n";
                    }
                }
                else
                {
                    tbMessages.Text += "No new messages @: " + System.DateTime.Now + "\n";
                }
            }
            catch (System.Net.WebException we)
            {
                MessageBox.Show(we.Message);
            }
        }
    }

Anyone?


The WebClient response is processed on the UI thread - so you don't need the lock that you have in your event handler.

For your particular problem - is this just occurring in the emulator? I've seen quite a few timer issues with the emulator - but never anything similar on the real phone.

As an aside, I believe in general it's better to use HttpWebRequest rather than WebClient - see the explanation here of webclient using the UI thread Silverlight Background Thread using WebClient - for your particular code I don't think this will be a problem.


If using

        System.Windows.Threading.DispatcherTimer myDispatcherTimer = new System.Windows.Threading.DispatcherTimer();
        myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 5000);
        myDispatcherTimer.Tick += new EventHandler(messagePolling);
        myDispatcherTimer.Start();

instead of

new System.Threading.Timer(messagePolling, null, 0, 5000);   // every 5 seconds

is working fine =)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜