Enforce an async method to be called once

前端 未结 3 1278
广开言路
广开言路 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条回答
  •  -上瘾入骨i
    2020-12-29 10:14

    Yes. Use Stephen Cleary's AsyncLazy (available on the AsyncEx nuget):

    private static readonly AsyncLazy myResource = new AsyncLazy(
        async () => 
        { 
            var ret = new MyResource(); 
            await ret.InitAsync(); 
            return ret; 
        }
    );
    
    public async Task UseResource()
    {
        MyResource resource = await myResource;
        // ...
    }
    

    Or the visual studio SDK's AsyncLazy if you prefer a Microsoft implementation.

提交回复
热议问题