gpt4 book ai didi

c# - Windows Phone 8.1 中后台任务显示对话框的问题

转载 作者:可可西里 更新时间:2023-11-01 09:20:14 27 4
gpt4 key购买 nike

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

    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();

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

最佳答案

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();
});

关于c# - Windows Phone 8.1 中后台任务显示对话框的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25683998/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com