Skip to main content
 首页 » 编程设计

c#之正确使用 Async/Await

2024年02月06日11JeffreyZhao

<分区>

这是我对 async/await 的实现,但我不确定我做的是否正确。

代码按预期工作,但我希望有人检查这一小段代码以指出任何错误。

public class DbUtils 
{ 
 
    public static List<string> GetDataSources() 
    { 
        //I have removed some logic from here as it's not important to my question 
        List<string> names = new List<string>(); 
        names = SomeClass.SomeLongSystemMethod(); 
        return names; 
    } 
 
    public static async Task<List<string>> GetDataSourcesAsync() 
    { 
        //This is a place where I have my doubts 
        return await Task.Run(() => 
        { 
            return GetDataSources(); 
        }); 
    } 
} 
 
public class SomeOtherClass 
{ 
    private async void BT_RefreshServerName_Click(object sender, EventArgs e) 
    { 
        CB_ServerName.DataSource = await DbUtils.GetDataSourcesAsync(); 
    } 
} 

编辑:

我的新版本代码如下所示。

public class SomeOtherClass 
{ 
    private async void BT_RefreshServerName_Click(object sender, EventArgs e) 
        { 
            try 
            { 
                BT_RefreshServerName.Enabled = false; 
 
                //.ConfigureAwait(true) (this is a default) is to attempt to 
                //marshal the continuation back to the original context as the 
                //result is used to update UI.                     
                CB_ServerName.DataSource = await Task.Run( 
                 () => DbUtils.GetDataSources()).ConfigureAwait(true); 
            } 
            catch (Exception ex) 
            { 
                MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK); 
            } 
            finally 
            { 
                BT_RefreshServerName.Enabled = true; 
            } 
        } 
    } 
} 
 
public class DbUtils 
{ 
 
    public static List<string> GetDataSources() 
    { 
        //Some logic 
 
        List<string> names = new List<string>(); 
        names = SomeClass.SomeLongSystemMethod(); 
        return names; 
    } 
}