Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# IDbCommand接口中缺少异步功能_C#_Asynchronous_Idbcommand - Fatal编程技术网

C# IDbCommand接口中缺少异步功能

C# IDbCommand接口中缺少异步功能,c#,asynchronous,idbcommand,C#,Asynchronous,Idbcommand,这是向IDbCommand接口添加异步功能的合理方法吗 public async static Task ExecuteReaderAsync(此IDbCommand self){ DbCommand DbCommand=self作为DbCommand; if(dbCommand!=null){ 返回wait dbCommand.ExecuteReaderAsync().ContinueWith(task=>(IDataReader)task.Result); }否则{ 返回等待任务。运行(()

这是向IDbCommand接口添加异步功能的合理方法吗

public async static Task ExecuteReaderAsync(此IDbCommand self){
DbCommand DbCommand=self作为DbCommand;
if(dbCommand!=null){
返回wait dbCommand.ExecuteReaderAsync().ContinueWith(task=>(IDataReader)task.Result);
}否则{
返回等待任务。运行(()=>self.ExecuteReader());
}
}
具体来说,我不完全确定使用“ContinueWith”来伪造“Task”的协方差会有什么影响

另外,在传入的“self”实例不从DbCommand继承的不太可能的情况下,在执行“self.ExecuteReader()”期间,线程池线程是否会被消耗和阻塞

为我的IDb扩展异步支持的完整实现干杯。


谢谢

如果您使用的是.NET 4.5,您缺少了
async
wait
。您尝试的方式是正确的,希望您单独处理连接

public static async Task<IDataReader> ExecuteReaderAsync(this IDbCommand self)
{
    var dbCommand = self as DbCommand;
    if (dbCommand != null)
    {
        return await dbCommand.ExecuteReaderAsync();
    }

    return await Task.Run(() => self.ExecuteReader());
}
公共静态异步任务ExecuteReaderAsync(此IDbCommand self)
{
var dbCommand=self作为dbCommand;
if(dbCommand!=null)
{
返回wait-dbCommand.ExecuteReaderAsync();
}
返回等待任务。运行(()=>self.ExecuteReader());
}

仅仅因为它更干净,我会利用您正在使用
async
wait
来消除
ContinueWith()中的强制转换<代码>等待
用于任务时,计算结果为类型为
TResult
的对象。我打算建议使用语法
return(IDataReader)wait dbCommand.ExecuteReaderAsync(),但我记得编译器已经知道
DbDataReader
IDataReader
。在VS 2013和VS 2015预览版中进行了测试(不确定您的目标是什么,但我认为所有支持
await
的C#编译器都应该使用此功能):


你打算将你的库作为nuget包发布吗?
public async static Task<IDataReader> ExecuteReaderAsync(this IDbCommand self) {
    DbCommand dbCommand = self as DbCommand;
    if (dbCommand != null) {
        return await dbCommand.ExecuteReaderAsync();
    } else {
        return await Task.Run(() => self.ExecuteReader());
    }
}
public async static Task<IDataReader> ExecuteReaderAsync(this IDbCommand self) {
    if (self is DbCommand dbCommand) {
        return await dbCommand.ExecuteReaderAsync();
    } else {
        return await Task.Run(() => self.ExecuteReader());
    }
}