1

我有以下方法返回一个IAsyncEnumerable<T>

async IAsyncEnumerable<T> RunReport()
{
    var handler = new HttpClientHandler();

    var client = new HttpClient(handler);
    client.BaseAddress = new Uri("");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var settings = new JsonSerializerSettings();

    var jsonFormatter = new JsonMediaTypeFormatter() { SerializerSettings = settings };

    var requestMessage = new HttpRequestMessage(HttpMethod.Get, "api/controler");
    var response = await client.SendAsync(requestMessage);

    response.EnsureSuccessStatusCode();

    using (var stream = await response.Content.ReadAsStreamAsync())
    {
        using (var reader = new StreamReader(stream))
        {
            while (!reader.EndOfStream)
            {
                var linesJson = await reader.ReadLineAsync();
                var line = JsonConvert.DeserializeObject<List<T>>(linesJson, jsonFormatter.SerializerSettings);

                foreach (var line in lines)
                    yield return line;
            }
        }
    }
}

我想使用SqlBulkCopy'sWriteToServerAsync方法将该结果流传输到数据库,但无法弄清楚如何将其转换为's 重载列表IDataReader中的任何其他类型。WriteToServerAsync

我愿意使用除批量复制之外的其他东西,只要它性能合理。

4

1 回答 1

0

使用此处的示例,我提出了一个采用 IAsyncEnumerable 并实现接口的适当部分的 IDataReader。

public class GenericDataReader<T> : IDataReader where T : class
{
    private readonly IAsyncEnumerator<T> _asychEnumerator;
    private readonly List<FieldInfo> _fields = new List<FieldInfo>();

    public GenericDataReader(IAsyncEnumerable<T> asyncEnumerable)
    {
        _asychEnumerator = asyncEnumerable.GetAsyncEnumerator();

        foreach (FieldInfo fieldinfo in typeof(T).GetFields(BindingFlags.Instance | BindingFlags.Public))
        {
            _fields.Add(fieldinfo);
        }
    }

    public int FieldCount => _fields.Count;

    public void Dispose() { Close(); }

    public bool Read()
    {
        return _asycEnumerator.MoveNextAsync().Result;
    }

    public async void Close(){ await _asychEnumerator.DisposeAsync(); }

    public Type GetFieldType(int i){ return _fields[i].FieldType; }

    public string GetName(int i) { return _fields[i].Name; }

    public object GetValue(int i){ return _fields[i].GetValue(_asychEnumerator.Current); }
}   

我仍在研究该示例,但对 Read() 方法的实现有点了解。

于 2020-01-31T16:00:49.557 回答