Best asynchronous while method

前端 未结 4 2035
离开以前
离开以前 2020-12-28 14:57

I need to write some asynchronous code that essentially attempts to repeatedly talk to and initialise a database. Quite often the first attempt will fail hence the requirem

4条回答
  •  再見小時候
    2020-12-28 15:24

    You don't really need WaitItForWork method, just await for a database initialization task:

    async Task Run()
    {
        await InitializeDatabase();
        // Do what you need after database is initialized
    }
    
    async Task InitializeDatabase()
    {
        // Perform database initialization here
    }
    

    If you have multiple pieces of code that call to WaitForItToWork then you need to wrap database initialization into a Task and await it in all workers, for example:

    readonly Task _initializeDatabaseTask = InitializeDatabase();
    
    async Task Worker1()
    {
        await _initializeDatabaseTask;
        // Do what you need after database is initialized
    }
    
    async Task Worker2()
    {
        await _initializeDatabaseTask;
        // Do what you need after database is initialized
    }
    
    static async Task InitializeDatabase()
    {
        // Initialize your database here
    }
    

提交回复
热议问题