gpt4 book ai didi

c# - SqlBulkCopy 抛出 "Operation is not valid due to the current state of the object"

转载 作者:行者123 更新时间:2023-12-04 07:31:11 26 4
gpt4 key购买 nike

我正在尝试为 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;
}
我的问题是,当我将数据读取器传递到 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 将用于稍后继续工作以检查它。
CLR 可以 不是 如果您不这样做,请稍后检查结果 await电话。
由于您想同步运行此代码(至少从我可以通过使用 .Result 假设),我已经包含了一个应该同步为您工作的解决方法。
考虑使用 .AsTask().Result而不是 .Result .这将强制 CLR 在返回结果之前等待任务完成。

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

关于c# - SqlBulkCopy 抛出 "Operation is not valid due to the current state of the object",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67921770/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com