Ram*_*esh 0 c# asynchronous using async-await c#-7.0
我正要使用下面的 C# 代码。
await using (var producerClient = new EventHubProducerClient(ConnectionString, EventHubName))
{
using EventDataBatch eventBatch = await producerClient.CreateBatchAsync();
eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes(eventData)));
await producerClient.SendAsync(eventBatch);
}
Run Code Online (Sandbox Code Playgroud)
但是在构建服务器中这会失败,因为上面是 C# 8.0 代码并且构建服务器只支持 C# 7.0 代码。有人可以帮我将上面的代码从 C# 8.0 转换为 C# 7.0,因为我无法让它工作吗?
Ste*_*ary 11
从长远来看,更新构建服务器当然更好。无论如何,您迟早需要这样做。
C# 8.0 有using 声明,它改变了这个:
using var x = ...;
...
Run Code Online (Sandbox Code Playgroud)
进入这个:
using (var x = ...)
{
...
}
Run Code Online (Sandbox Code Playgroud)
此代码中的另一个 C# 8.0 功能是await using,它会像这样转换代码:
await using (var x = ...)
{
...
}
Run Code Online (Sandbox Code Playgroud)
变成类似的东西:
var x = ...;
try
{
...
}
finally
{
await x.DisposeAsync();
}
Run Code Online (Sandbox Code Playgroud)
手动应用这两种转换可以为您提供:
var producerClient = new EventHubProducerClient(ConnectionString, EventHubName);
try
{
using (EventDataBatch eventBatch = await producerClient.CreateBatchAsync())
{
eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes(eventData)));
await producerClient.SendAsync(eventBatch);
}
}
finally
{
await producerClient.DisposeAsync();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
315 次 |
| 最近记录: |