【发布时间】:2014-08-12 22:40:48
【问题描述】:
这是我的 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;
}
}
【问题讨论】:
-
这个问题似乎跑题了,因为它属于codereview.stackexchange.com
-
@RemusRusanu 我不知道有一个单独的部分。谢谢你告诉我这件事。下次我将使用 codereview 部分。
-
如果您在等待任务后不做任何事情,您可以简单地返回任务。这将有助于优化您的代码,因为它不需要创建代理任务。所以GetDataSourcesAsync可以改成
return Task.FromResult(GetDataSources());然后去掉函数上的async修饰符 -
@JLevett 谢谢!这正是我正在寻找的答案。干杯
标签: c# async-await .net-4.5