SqlBulkCopy 抛出“由于对象的当前状态,操作无效”

问题描述

我正在尝试为 IAsyncEnumerable<T> 集合创建自定义 DataReader,以便通过 sqlBulkcopy 将记录加载到数据库表中。我正在遵循此问题中概述的代码示例和解决方案 - How to use SqlBulkCopy to write an IAsyncEnumerable

这是我的 DataReader 的要点:

internal sealed class AsyncEnumerableDataReader<T> : IDataReader
    {
        private readonly IAsyncEnumerator<T> _asyncEnumerator;
        private readonly List<PropertyInfo> _properties = new List<PropertyInfo>();
        private bool _isClosed = false;

        public AsyncEnumerableDataReader(IAsyncEnumerable<T> asyncEnumerable)
        {
            _asyncEnumerator = asyncEnumerable.GetAsyncEnumerator();

            foreach (PropertyInfo propertyInfo in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                _properties.Add(propertyInfo);
            }
        }

 //.... Other method implementations here

public bool Read() => _asyncEnumerator.MoveNextAsync().Result;
}

我的问题是,当我将 datareader 传递给 sqlBulkcopy.WritetoServerAsync(reader) 方法时,在第一次调用 DataReader.Read() 时会引发以下错误

system.invalidOperationException: 'Operation is not valid due to the current state of the object.'

有人知道我的代码哪里出了问题吗?

解决方法

当您将 .ResultValueTask<T> 一起使用时,它不会阻塞当前线程以等待结果(在您的情况下为 bool)。>

如果 ValueTask<T> 在第一次调用期间没有及时完成,它将返回一个 Task,CLR 将使用它来继续工作以检查它。

当您不await调用时,CLR 可以检查结果。

由于您希望同步运行此代码(至少从我使用 .Result 可以假设的情况来看),因此我提供了一个可以同步为您工作的解决方法。

考虑使用 .AsTask().Result 而不是 .Result。这将强制 CLR 在返回结果之前等待任务完成。

public bool Read() => _asyncEnumerator.MoveNextAsync().AsTask().Result;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...