问题
I was wondering how to implement this Android AsyncTask using .NET's async libraries:
public class LoadRecordTask : AsyncTask
{
private Activity1 _context;
private int _recordId;
public LoadRecordTask( Activity1 outerActivity, int recordId )
{
_context = outerActivity;
_recordId = recordId;
}
protected override void OnPreExecute()
{
base.OnPreExecute();
_progressDialog = Android.App.ProgressDialog.Show( _context , "", "Loading record {0}", _recordId );
}
protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
{
_bSuccess = LoadRecord( _recordId );
if( !_bSuccess )
{
return false;
}
return true;
}
protected override void OnPostExecute(Java.Lang.Object result)
{
base.OnPostExecute(result);
if( !_bSuccess )
{
_progressDialog.SetMessage( "Error loading recording." );
}
_progressDialog.Dismiss();
}
}
回答1:
The AsyncTask you are using could be translated to something like:
_progressDialog = ProgressDialog.Show( _context , "", "Loading record {0}", _recordId );
if (await LoadRecord(_recordId))
_progressDialog.Dismiss();
else
_progressDialog.SetMessage( "Error loading recording." );
Where LoadRecord could be returning Task<bool> and the internals running inside of Task. Otherwise you can just wrap the LoadRecord method you are currently using in a Task to make it run async.
private Task<bool> LoadRecord(int recordId)
{
return Task<bool>.Run(() =>
{
//Do stuff here to fetch records
return true;
});
}
The method you are calling await from needs to be marked as async. I.e.:
private async void MyAwesomeAsyncMethod() {}
来源:https://stackoverflow.com/questions/21882631/convert-asynctask-to-task-in-monodroid-c