首页 > 解决方案 > 在 AlertDialog 中的 TaskCompletionSource 上设置结果时出错

问题描述

我创建了一个 AlertDialog.Builer,第二次显示弹出窗口并与之交互时出现错误。

我创建了这样的对话框:

  public Task<bool?> ShowAsync(string title, string message, string okContent = null, string cancelContent = null, bool okBeforeCancel = false)
        {
            if (_tcs is null)
            {
                _tcs = new TaskCompletionSource<bool?>();
            }

            if (_dialog != null)
            {
                Dismiss();
            }

            var alertBuilder = BuildAlertView(title, message, okContent, cancelContent, _tcs, okBeforeCancel);
            _dialog = alertBuilder.Create();
            _dialog.Show();
            return _tcs.Task;
        }

  private static AlertDialog.Builder BuildAlertView(string title, string message, string ok, string cancel, TaskCompletionSource<bool?> tcs, bool okBeforeCancel)
        {
            var mvxTopActivity = Mvx.Resolve<IMvxAndroidCurrentTopActivity>();

                var builder = new AlertDialog.Builder(mvxTopActivity.Activity)
                    .SetCustomTitle(CreateTitle(title, mvxTopActivity))
                    .SetMessage(message)
                    .SetCancelable(false);

                AddButtons(builder, tcs, ok, cancel, okBeforeCancel);
                return builder;
        }

  private static void AddButtons(AlertDialog.Builder builder, TaskCompletionSource<bool?> tcs, string ok, string cancel, bool okBeforeCancel)
        {
            (ok, cancel) = okBeforeCancel ? (cancel, ok) : (ok, cancel);
            var (okResult, cancelResult) = okBeforeCancel ? (false, true) : (true, false);

            if (!IsNullOrWhiteSpace(ok))
            {
                builder.SetCancelable(false);
                builder.SetPositiveButton(ok, (s, e) =>
                {
                    tcs.SetResult(okResult);
                });
            }

            if (!IsNullOrWhiteSpace(cancel))
            {
                builder.SetCancelable(true);
                builder.SetNegativeButton(cancel, (s, e) =>
                {
                    tcs.SetResult(cancelResult);
                });
            }
        }

我第一次显示弹出窗口时,一切都按预期工作。第二次,它在 tcs.SetResult() 方法处崩溃。

标签: androidxamarin.androidandroid-alertdialog

解决方案


根据我的评论,这应该有助于解决您遇到的问题。

public Task<bool?> ShowAsync(Activity activity, string title, string message, string okContent = null, string cancelContent = null, bool okBeforeCancel = false)
{
    if (_tcs is null)
    {
        _tcs = new TaskCompletionSource<bool?>();
    }

    if (_dialog != null)
    {
        Dismiss();
    }

    activity.RunOnUiThread(()=>{
        var alertBuilder = BuildAlertView(title, message, okContent, cancelContent, _tcs, okBeforeCancel);
        _dialog = alertBuilder.Create();
        _dialog.Show();
    });

    return _tcs.Task;
}

推荐阅读