Enforce an async method to be called once

前端 未结 3 1277
广开言路
广开言路 2020-12-29 09:53

Say I have a class that needs to perform some async initialization using an InitializeAsync() method. I want to make sure that the initialization is performed only once. If

3条回答
  •  無奈伤痛
    2020-12-29 10:05

    I'd go with AsyncLazy (slightly modified version):

    public class AsyncLazy : Lazy> 
    { 
        public AsyncLazy(Func valueFactory) : 
            base(() => Task.Run(valueFactory)) { }
    
        public AsyncLazy(Func> taskFactory) : 
            base(() => Task.Run(() => taskFactory())) { } 
    
        public TaskAwaiter GetAwaiter() { return Value.GetAwaiter(); } 
    }
    

    And consume it like this:

    private AsyncLazy asyncLazy = new AsyncLazy(async () =>
                                        { 
                                            await DoStuffOnlyOnceAsync()
                                            return true;
                                        });
    

    Note i'm using bool simply because you have no return type from DoStuffOnlyOnceAsync.

    Edit:

    Stephan Cleary (of course) also has an implementation of this here.

提交回复
热议问题