Convert AsyncTask to Task in Monodroid/C#

喜夏-厌秋 提交于 2019-12-11 05:45:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!