简体   繁体   中英

Async initialization of properties

I am trying to refactor loading individual properties with an async method. The loader function is this:

public static async Task<Preferences> GetPreferences( string key ) ...

It is currently used like this

GetPreferences( "SettingsUploadStale" ).ContinueWith( task =>
    App.MayUploadStale = Convert.ToBoolean( task.Result?.Value )
);

I have a bunch of these calls and want to hide and reuse the ContinueWith, Convert, etc. I came up with this function

public static void LoadPreferenceAsync( string key, ref bool store ) {
    GetPreferences( key ).ContinueWith( task =>
        store = Convert.ToBoolean( task.Result?.Value )
    );
}

LoadPreferenceAsync( "SettingsUploadStale", ref App.MayUploadStale);

Which fails to compile with "Cannot use ref, out, or in parameter 'store' inside an anonymous method, lambda expression, query expression, or local function" .

So what is the recommended way to do this? I don't want to await tasks so that it can happen in background and I can load them all in parallel. Don't want to use unsafe code or pointers, because this is a Xamarin app and Xamarin is too unstable already without that stuff.

You can await tasks and load them all in parallel. Try

var taskSettingsUploadStale = GetPreferences("SettingsUploadStale");
var taskSomethingElse = GetPreferences("SomethingElse");
var taskSomeOtherThing = GetPreferences("SomeOtherThing");

Task.WaitAll(taskSettingsUploadStale, taskSomethingElse, taskSomeOtherThing);

App.MayUploadStale = Convert.ToBoolean( taskSettingsUploadStale.Result?.Value);
// get and use remaining results

It is not an elegant solution and not tested but you could rewrite your function as

public static void LoadPreferenceAsync(string key, Action<Task<Preferences>> continueAction){
     GetPreferences(key).ContinueWith(task => continueAction);
}

and use it like:

Action<Task<Preferences>> continueAction = task => App.MayUploadStale = Convert.ToBoolean(task.Result?.Value);
LoadPreferenceAsync("SettingsUploadStale", continueAction);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM