我正在编写简单的类,它将连接到SQL DB并从中获取数据。
我想让它异步,但我在异步编程方面遇到了一些问题。
代码:
public async Task<ICommand> ExecuteAsync(SqlConnection connection)
{
var cmd = new SqlCommand(Query);
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
if(connection.State != ConnectionState.Open)
await connection.OpenAsync();
using (SqlDataReader sqlDataReader = await cmd.ExecuteReaderAsync())
{
if (sqlDataReader.HasRows)
{
while (await sqlDataReader.ReadAsync())
{
Entry = new Entry();
Entry.ID = (int) sqlDataReader["ID"];
Entry.User = (string) sqlDataReader["UserName"];
object o = sqlDataReader["EntryType"];
Entry.EntryType = o.Equals("Enter") ? EntryType.Enter : EntryType.Leave;
Entry.DateTime = (DateTime) sqlDataReader["EntryDate"];
}
}
}
使用此代码,调试器始终在OpenAsync()方法后停止执行。它没有达到下一个声明。
你能告诉我我做错了什么吗?
此致
- 编辑 - 我现在在桌面上运行它(简单单元测试) 我添加了try-catch来处理异常。
我的最小样本:
ExecuteAsync方法:
public async Task<ICommand> ExecuteAsync(SqlConnection connection)
{
var cmd = new SqlCommand(Query);
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
if(connection.State != ConnectionState.Open)
await connection.OpenAsync().ConfigureAwait(false);
using (SqlDataReader sqlDataReader = await cmd.ExecuteReaderAsync().ConfigureAwait(false))
{
if (sqlDataReader.HasRows)
{
while (await sqlDataReader.ReadAsync().ConfigureAwait(false))
{
Entry = new Entry();
Entry.ID = (int) sqlDataReader["ID"];
// Entry.User =(string)sqlDataReader [&#34; UserName&#34;]; // object o = sqlDataReader [&#34; EntryType&#34;]; // Entry.EntryType = o.Equals(&#34;输入&#34;)? EntryType.Enter:EntryType.Leave; // Entry.DateTime =(DateTime)sqlDataReader [&#34; EntryDate&#34;]; } } } 归还这个; }
调用此方法:
public void ExecuteCommandAsync(ICommand command, ReadFinished continueWith)
{
if(continueWith == null)
throw new NullReferenceException("Parameter 'continueWith' cannot be null");
command.ExecuteAsync(_connection).ContinueWith(task => continueWith(task.Result)).ConfigureAwait(false);
}
我的测试用例:
public void TestMethod1()
{
TimeTableDBConnector.DbConnector connector = new DbConnector(null);
var getEntryByIDCommand = new GetEntryByIDCommand(1);
ICommand result;
try
{
connector.ExecuteCommandAsync(getEntryByIDCommand, ContinueWith );
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private void ContinueWith(ICommand command)
{
GetEntryCommand cmd = (GetEntryCommand) command;
}
答案 0 :(得分:0)
大多数测试框架都支持异步测试,因此如果您更改ExecuteCommandAsync
方法以返回Task
,您应该能够将测试标记为async
和await
ExecuteCommandAsync
。试一试:
async void TestMethod1()
{
TimeTableDBConnector.DbConnector connector = new DbConnector(null);
var getEntryByIDCommand = new GetEntryByIDCommand(1);
ICommand result;
try
{
await connector.ExecuteCommandAsync(getEntryByIDCommand, ContinueWith );
}
catch (Exception e)
{
Console.WriteLine(e);
}
}