当Thread运行时,BackKey不工作。为什么?

时间:2012-01-04 08:28:31

标签: windows-phone-7

PageA导航到PageB 有一个线程正在为HttpWebRequest运行。 线程运行时,返回键无效。 PageB代码:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        Debug.WriteLine("OnNavigatedTo");
        //base.OnNavigatedTo(e);
        DoWork();
    }

void DoWork()
    {
        t = new Thread(new ThreadStart(() =>
        {
            request = WebRequest.Create("http://www.google.com") as HttpWebRequest;
            request.BeginGetResponse(new AsyncCallback(AsyncBack), request);
        }));
        t.IsBackground = true;
        t.Start();
    }


void AsyncBack(IAsyncResult ias)
    {
        HttpWebRequest req = (HttpWebRequest)ias.AsyncState;
        using (HttpWebResponse res = req.EndGetResponse(ias) as HttpWebResponse)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                this.PageTitle.Text = res.ContentLength.ToString();
                long length = res.ContentLength;
                for (long i = 0; i < length; i++)
                {
                    //here imitate a long time for working
                    Debug.WriteLine(i);
                    if (i == length)
                    {
                        break;
                    }
                }
                Debug.WriteLine(res.ContentLength);
            });
        }
    }

Back Method无效,直到Method AsyncBack()完成。 '后退键无效'是否在触摸后退键时应用程序未返回到PageA,直到方法AsyncBack()完成。 为什么?帮帮我?

2 个答案:

答案 0 :(得分:2)

为什么你在自定义线程中包含异步请求的血腥地狱?这甚至没有意义。

然后,你的问题也没有多大意义,但很可能错误与请求试图通过调用操作有关。调度员,在错误的页面上。

答案 1 :(得分:1)

在您的代码中,您长时间阻止UI线程,因此您无法导航回页面,因为它也会在UI线程上发生,只将Dispatcher放入无法在UI上执行的代码

    void DoWork()
    {
        HttpWebRequest request = WebRequest.Create("http://www.googl.com") as HttpWebRequest;
        request.BeginGetResponse(new AsyncCallback(AsyncBack), request);
    }

    void AsyncBack(IAsyncResult ias)
    {
        HttpWebRequest req = (HttpWebRequest)ias.AsyncState;
        using (HttpWebResponse res = req.EndGetResponse(ias) as HttpWebResponse)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                this.PageTitle.Text = res.ContentLength.ToString();
            });

            long length = res.ContentLength;
            for (long i = 0; i < length; i++)
            {
                long i_ = i;
                //here imitate a long time for working
                Thread.Sleep(10);
                this.Dispatcher.BeginInvoke(() =>
                {                        
                    this.PageTitle.Text = i_.ToString();
                });
                if (i == length)
                {
                    break;
                }
            }
            Debug.WriteLine(res.ContentLength);                
        }
    }