gRPC multithreading example (#26866)

Co-authored-by: Wade Pickett <wpickett@microsoft.com>
pull/26868/head
James Newton-King 2022-08-30 08:14:57 +08:00 committed by GitHub
parent 2ed3f8f6a1
commit 15d0998806
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 40 additions and 0 deletions

View File

@ -328,6 +328,46 @@ A gRPC call ends on the server once the gRPC method exits. The following argumen
If a gRPC method starts background tasks that use these types, it must complete the tasks before the gRPC method exits. Continuing to use the context, stream reader, or stream writer after the gRPC method exists causes errors and unpredictable behavior.
In the following example, the server streaming method could write to the response stream after the call has finished:
```csharp
public override async Task StreamingFromServer(ExampleRequest request,
IServerStreamWriter<ExampleResponse> responseStream, ServerCallContext context)
{
_ = Task.Run(async () =>
{
for (var i = 0; i < 5; i++)
{
await responseStream.WriteAsync(new ExampleResponse());
await Task.Delay(TimeSpan.FromSeconds(1));
}
});
await PerformLongRunningWorkAsync();
}
```
For the previous example, the solution is to await the write task before exiting the method:
```csharp
public override async Task StreamingFromServer(ExampleRequest request,
IServerStreamWriter<ExampleResponse> responseStream, ServerCallContext context)
{
var writeTask = Task.Run(async () =>
{
for (var i = 0; i < 5; i++)
{
await responseStream.WriteAsync(new ExampleResponse());
await Task.Delay(TimeSpan.FromSeconds(1));
}
});
await PerformLongRunningWorkAsync();
await writeTask;
}
```
## Additional resources
* <xref:grpc/basics>