【问题标题】:Problems with show dialog on Background task in windows phone 8.1windows phone 8.1中后台任务显示对话框的问题
【发布时间】:2014-09-05 10:39:21
【问题描述】:

我有此代码用于在后台方法中执行 httpwebrequest 和响应,我只想在下载 zip 崩溃并且我的代码进入此捕获时显示对话框以获取信息...

    private void DoSincroFit()
    {
        HttpWebRequest request = HttpWebRequest.CreateHttp(url);
        request.BeginGetResponse(new AsyncCallback(playResponseAsync), request);
    }

    public async void playResponseAsync(IAsyncResult asyncResult)
    {
        //Declaration of variables
        HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;

        try
        {
            string fileName = "sincrofit.rar";

            using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
            {
                byte[] buffer = new byte[1024];


                var newZipFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
                var newZipFile = await KnownFolders.DocumentsLibrary.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                using (var writeStream = await newZipFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (var outputStream = writeStream.GetOutputStreamAt(0))
                    {
                        using (var dataWriter = new DataWriter(outputStream))
                        {
                            using (Stream input = webResponse.GetResponseStream())
                            {
                                var totalSize = 0;
                                for (int size = input.Read(buffer, 0, buffer.Length); size > 0; size = input.Read(buffer, 0, buffer.Length))
                                {
                                    dataWriter.WriteBytes(buffer);
                                    totalSize += size;    //get the progress of download
                                }
                                await dataWriter.StoreAsync();
                                await outputStream.FlushAsync();
                                dataWriter.DetachStream();
                            }
                        }
                    }
                }

            }
        }
        catch
        {
           SMethods.Message_Dialog("Download has stopped!","Error");
        }
    }

但是当我的代码从这个类执行这个方法时:

class StandarMethods
{
public async void Message_Dialog(string text, string title)
    {
        //Declaration of variables
        MessageDialog MDialog = new MessageDialog(text, title);

        await MDialog.ShowAsync();
    }
}

最后我的应用程序在尝试执行时崩溃:

await MDialog.ShowAsync();

这个等待后台任务...有人可以帮助我吗?是时候使用事件处理程序了吗?为什么?如何?提前致谢!

【问题讨论】:

    标签: c# windows windows-phone-8 background task


    【解决方案1】:

    Merli 你的问题是你试图从后台访问 UI 线程以向用户显示对话框所以使用 Dispatcher 这个基本示例是:-

    // This is for silverlight part
        Deployment.Current.Dispatcher.BeginInvoke(delegate
        {
          var mbr = MessageBox.Show("Are you sure you want to leave this page?", "Warning",      
          MessageBoxButton.OKCancel);
    
          if(mbr == MessageBoxResult.OK)
          {   OK pressed  } 
          else
          {   Cancel pressed  }
    
        });
    

    对于 winrt 部分 -

    CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
        dispatcher.RunAsync(CoreDispatcherPriority.Normal, async()=>{
              // UI code goes here
              //Declaration of variables
            MessageDialog MDialog = new MessageDialog(text, title);
            await MDialog.ShowAsync();
        });
    

    【讨论】:

    • 完美!但是这段代码给了我一点错误......错误:“对象引用没有设置和对象的实例”这是一个密封类,没有构造方法。知道吗?谢谢大家!
    • 这段代码不起作用,因为视觉告诉我:“名称“部署”在实际上下文中不存在”,当我使用 Visual Studio 帮助时,然后导出这个库:Windows.Phone .Management.Deployment.Current.Dispatcher.BeginInvoke... 但是视觉上告诉我当前不存在并且是一个错误。最后,Windows phone 8 中不存在 MessageBox 控件。谢谢大家!
    • 您是为 WP8.1 silverlight 还是 WP8.1 winrt 模板开发?
    • 和第一个代码:CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { //声明变量 SMethods.Message_Dialog("下载已停止!", "Error"); });在调度程序上分配值时在第一行失败。谢谢大家
    • 我不太清楚,抱歉,我是 wp 的新手开发者,silverlight 是 nuguet 包还是库?如果是,那么我使用 winrt 模板,我怎么知道呢?谢谢大家!
    【解决方案2】:

    解决了,我的最终代码在这里:

        private CoreDispatcher dispatcher;
    
        private void DoSincroFit()
        {
            HttpWebRequest request = HttpWebRequest.CreateHttp(url);
    
            //Add headers to request
            request.Headers["Type"] = "sincrofit";
            request.Headers["Device"] = "1";
            request.Headers["Version"] = "0.000";
            request.Headers["Os"] = "WindowsPhone";
    
            dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
            request.BeginGetResponse(new AsyncCallback(playResponseAsync), request);
        }
    
        public async void playResponseAsync(IAsyncResult asyncResult)
        {
            //Declaration of variables
            HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;
    
            try
            {
                //For download file  with stream
                //http://social.msdn.microsoft.com/Forums/windowsapps/en-US/de96a61c-e089-4595-8349-612be5d23ee6/download-file-with-httpwebrequest?forum=winappswithcsharp
                string fileName = "sincrofit.rar";
    
                using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
                {
                    byte[] buffer = new byte[1024];
    
                    //For acces Local folder of phone device
                    //http://social.msdn.microsoft.com/Forums/windowsapps/en-US/ec99721c-6565-4ce9-b6cc-218f2265f9c7/what-is-the-uri-of-an-isolatedstorage-file?forum=wpdevelop
                    var newZipFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
    
                    using (var writeStream = await newZipFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        using (var outputStream = writeStream.GetOutputStreamAt(0))
                        {
                            using (var dataWriter = new DataWriter(outputStream))
                            {
                                using (Stream input = webResponse.GetResponseStream())
                                {
                                    var totalSize = 0;
    
                                    for (int size = input.Read(buffer, 0, buffer.Length); size > 0; size = input.Read(buffer, 0, buffer.Length))
                                    {
                                        dataWriter.WriteBytes(buffer);
                                        totalSize += size;    //get the progress of download
    
                                        dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                                        {
                                            //Declaration of variables
                                            pBar.Value = sizeFit / totalSize * 100;
                                        });
                                    }
                                    await dataWriter.StoreAsync();
                                    await outputStream.FlushAsync();
                                    dataWriter.DetachStream();
                                }
                            }
                        }
                    }
    
                }
            }
            catch
            {
                dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                {
                    //Declaration of variables
                    SMethods.Message_Dialog("Download has stopped!", "Error");
                });
            }
        }
    

    感谢您抽出时间@loop!

    【讨论】:

      【解决方案3】:

      我的最终代码:

          private void DoSincroFit()
          {
              HttpWebRequest request = HttpWebRequest.CreateHttp(url);
      
              //Add headers to request
              request.Headers["Type"] = "sincrofit";
              request.Headers["Device"] = "1";
              request.Headers["Version"] = "0.000";
              request.Headers["Os"] = "WindowsPhone";
      
              request.BeginGetResponse(new AsyncCallback(playResponseAsync), request);
          }
      
          public async void playResponseAsync(IAsyncResult asyncResult)
          {
              //Declaration of variables
              HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;
      
              try
              {
                  string fileName = "sincrofit.rar";
      
                  using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
                  {
                      byte[] buffer = new byte[1024];
                      var newZipFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
      
                      using (var writeStream = await newZipFile.OpenAsync(FileAccessMode.ReadWrite))
                      {
                          using (var outputStream = writeStream.GetOutputStreamAt(0))
                          {
                              using (var dataWriter = new DataWriter(outputStream))
                              {
                                  using (Stream input = webResponse.GetResponseStream())
                                  {
                                      var totalSize = 0;
                                      for (int size = input.Read(buffer, 0, buffer.Length); size > 0; size = input.Read(buffer, 0, buffer.Length))
                                      {
                                          dataWriter.WriteBytes(buffer);
                                          totalSize += size;    //get the progress of download
                                      }
                                      await dataWriter.StoreAsync();
                                      await outputStream.FlushAsync();
                                      dataWriter.DetachStream();
                                  }
                              }
                          }
                      }
      
                  }
              }
              catch
              {
                  dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; //CRASH IN THIS LINE!
                  dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                  {
                      //Declaration of variables
                      SMethods.Message_Dialog("Download has stopped!", "Error");
                  });
              }
          }
      

      这是我的照片:

      谢谢大家!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多