xamarin android异步任务alertdialog

时间:2017-10-18 08:56:45

标签: xamarin.android async-await android-alertdialog

我使用visual studio 2015和xamarin android 我有一个带按钮和textview的小项目 单击按钮,我启动for(int = 0 ...)方法并尝试获取某个网页的内容并将此内容放入textview。这个方法是异步的

工作正常......

现在,我想在每个循环(for)上添加一个警告对话框并等待用户的响应? 我的问题是当我启动调试器时,(...)的方法为每个循环开始下载文件并显示每个循环的警告对话框......没有等待响应!

我是新任务,我确定我不明白如何使用或其他什么。 关于如何等待警报对话框响应的任何想法。

这是代码:

private async void Button_Click(object sender, EventArgs e)
{
    FindViewById<TextView>(Resource.Id.textView1).Text = "";
    await CreateMultipleTasksAsync();
    FindViewById<TextView>(Resource.Id.textView1).Text += "Control returned to startButton_Click.";
}

现在是异步方法的代码:

async Task CreateMultipleTasksAsync()
{
    HttpClient client = new HttpClient() { MaxResponseContentBufferSize = 1000000 };

    int max = 3;
    for (int i = 1; i <= max; i++)
    {
        // Create and start the tasks. As each task finishes, DisplayResults  
        // displays its length.
        Task<int> download1 = ProcessURLAsync("http://msdn.microsoft.com", client);
        Task<int> download2 = ProcessURLAsync("http://msdn.microsoft.com/en-us/library/hh156528(VS.110).aspx", client);
        Task<int> download3 = ProcessURLAsync("http://msdn.microsoft.com/en-us/library/67w7t67f.aspx", client);

        // Await each task. 
        int length1 = await download1;
        int length2 = await download2;
        int length3 = await download3;

        // Display the total count for the downloaded websites.
        int total = length1 + length2 + length3;
        FindViewById<TextView>(Resource.Id.textView1).Text += string.Format("\r\n\r\n Start {0} Tour for an total bytes returned:  {1}\r\n", i, total);

        //display alertDialog
        var x = await displayAlertDialogBox(i);
    }
}

以及警告对话框的最后一个代码

async Task<int> displayAlertDialogBox(int loop)
{
    int ret = 0;
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    //
    AlertDialog dialog = builder.Create();
    dialog.SetTitle("ALERT DIALOG");
    dialog.SetMessage(string.Format("COUNT {0} ITEM {1}", loop, "content"));
    dialog.SetCancelable(true);
    dialog.SetButton("OK button", (z, ev) =>
    {
        Toast.MakeText(this, string.Format("Ok button {0}", loop), ToastLength.Long).Show();
        ret = 99;
    });
    dialog.SetButton2("Cancel button", (z, ev) =>
    {
        Toast.MakeText(this, string.Format("Cancel button {0}", loop), ToastLength.Long).Show();
        ret = 1;
    });

    //
    dialog.Window.SetGravity(GravityFlags.Center);
    dialog.Show();

    //
    return (ret > 0) ? 1 : 0;
}

0 个答案:

没有答案