且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

转换的AsyncTask到任务MonoDroid的/ C#

更新时间:2023-10-22 13:52:40

在您使用的是可以转化为类似于的AsyncTask

  _progressDialog = ProgressDialog.Show(_context,,加载记录{0},_recordId);如果(的await LoadRecord(_recordId))
    _progressDialog.Dismiss();
其他
    _progressDialog.SetMessage(错误加载记录。);

其中, LoadRecord 可返回任务<布尔> 内部运行的内部任务。否则,你可以只是包装您目前正在使用的任务的 LoadRecord ,使其运行异步。

 私人任务<布尔> LoadRecord(INT的recordId)
{
    返回任务<布尔> .RUN(()=>
    {
        //做的东西在这里获取记录
        返回true;
    });
}

您是从需求的呼叫等待方法被标记为异步。即:

 专用异步无效MyAwesomeAsyncMethod(){}

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();
    }
}

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() {}