How to get returned result from function in Task.Run(Xamarin.Android)?

Viewed 881

I have the following views in my activity:

private Button btn;
private TextView txtView;

I have the following button click event:

private async void Btn_Click(object sender, System.EventArgs e)
{
     var mDialog = new ProgressDialog(this);
     mDialog.SetMessage("Loading data...");
     mDialog.SetCancelable(false);
     mDialog.Show();

     string str;

     await Task.Run((() => str = Foo()));
     // Alternatively
     // await Task.Delay(10000);

     mDialog.Dismiss();

     txtView.Text = str;


}

And I also have the following method:

string Foo()
{
    for (int i = 0; i < 10; i++)
    {
        Thread.Sleep(1000);
    }

    return "hello";
}

What I want is txtView.Text to be set to hello after the ProgressDialog is dismissed

2 Answers

Task.Run is not meant to be used like that what it does is Queues the specified work to run on the ThreadPool and returns a task or Task<TResult> handle for that work.

What you should do is make a method with a return type of Task<string> and then await that method

Then use that method to update your textview data

Solution:

You can set a dismiss listener by using SetOnDismissListener to do some work after the ProgressDialog is dismissed.

First, let your activity inherit from IDialogInterfaceOnDismissListener:

public class MainActivity : AppCompatActivity, IDialogInterfaceOnDismissListener

In your button click event, set your activity as the listener:

        private async void Btn_Click(object sender, System.EventArgs e)
    {
        var mDialog = new ProgressDialog(this);
        mDialog.SetMessage("Loading data...");
        mDialog.SetCancelable(false);

        //set your activity as the listener
        mDialog.SetOnDismissListener(this);

        mDialog.Show();
        await Task.Delay(10000);
        mDialog.Dismiss();

    }

Then you should implement the interface(IDialogInterfaceOnDismissListener) member OnDismiss, in this function, you can do whatever you want to do after the ProgressDialog is dismissed:

public void OnDismiss(IDialogInterface dialog)
{

    Toast.MakeText(this, "You used the 'SetOnDismissListener'.", ToastLength.Long).Show();

    txtView.Text = "hello";
}

You can refer:

IDialogInterfaceOnDismissListener

using-setondismisslistener-with-dialog

Related