Xamarin - 任务等待来自自定义对话框的输入

时间:2016-01-23 15:50:36

标签: android-asynctask xamarin xamarin.android alertdialog

我有一个下载任务,它通过4个步骤从网上下载数据,这些步骤被定义为异步任务并逐个运行。现在由于一些变化,我需要从任务2和3之间的自定义对话框中捕获用户输入。我已经编写了一个函数来捕获来自AlertDialog的输入。问题是两者之间的对话框显示,但它只是等待并停止处理并继续处理而不需要用户输入。代码是这样的:

async void button_click(......){
await function1();
await function2();
await function3();
await function4();
....do the data processing after that.
}

async Task<datatype> function1(){ ...processing step 1 }
async Task<datatype> function2(){

new AlertDialog.Builder(this)
              .SetPositiveButton("OK", (sender, args) =>
              {
                  string inputText = txtInput.Text;
              })
              .SetView(customView)
              .Show();

.... some more processing
}

我有什么方法可以停止处理,直到从AlertDialog或其他任何方式接收用户输入?

2 个答案:

答案 0 :(得分:5)

你可能会这样做:

public Task ShowDialog()
{
    var tcs = new TaskCompletionSource<bool>();
    new AlertDialog.Builder(this)
        .SetPositiveButton("OK", (sender, args) =>
        {
            string inputText = txtInput.Text;
            tcs.SetResult(true);
        })
        .SetView(customView)
        .Show();
    return tcs.Task;
}

然后你可以这样做:

await function1();
await ShowDialog();
await function2();

答案 1 :(得分:0)

缺少推杆任务

public Task<bool> ShowDialog()
{
    var tcs = new TaskCompletionSource<bool>();
    new AlertDialog.Builder(this)
        .SetPositiveButton("OK", (sender, args) =>
       {
           string inputText = txtInput.Text;
           tcs.SetResult(true);
       })
        .SetView(customView)
        .Show();
   return tcs.Task;
}