mirror of
https://github.com/Azure/DotNetty.git
synced 2026-10-20 07:37:46 +08:00
b2f10c28cb
Motivation: SocketException and ODE are being thrown when disconnecting gracefully. Modifications: - dismiss async read completion if it is done on inactive channel - do not attempt sync-reading from a socket that is not Connected - extra: fixing echo sample with better practices - extra: ReadListener for more natural test scenarios - extra: tweaked nbench spec to work in-loop Result: No excessive errors happen during graceful shutdown
61 lines
1.7 KiB
C#
61 lines
1.7 KiB
C#
// Copyright (c) Microsoft. All rights reserved.
|
|
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
|
|
namespace DotNetty.Tests.Common
|
|
{
|
|
using System;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
public static class TaskExtensions
|
|
{
|
|
public static Task<T> WithTimeout<T>(this Task<T> task, TimeSpan timeout)
|
|
{
|
|
if (task.IsCompleted || (timeout == Timeout.InfiniteTimeSpan))
|
|
{
|
|
return task;
|
|
}
|
|
|
|
return WithTimeoutInternal(task, timeout);
|
|
}
|
|
|
|
public static Task WithTimeout(this Task task, TimeSpan timeout)
|
|
{
|
|
if (task.IsCompleted || (timeout == Timeout.InfiniteTimeSpan))
|
|
{
|
|
return task;
|
|
}
|
|
|
|
return WithTimeoutInternal(task, timeout);
|
|
}
|
|
|
|
static async Task<T> WithTimeoutInternal<T>(Task<T> task, TimeSpan timeout)
|
|
{
|
|
using (var cts = new CancellationTokenSource())
|
|
{
|
|
if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)))
|
|
{
|
|
cts.Cancel();
|
|
return await task;
|
|
}
|
|
}
|
|
|
|
throw new TimeoutException();
|
|
}
|
|
|
|
static async Task WithTimeoutInternal(Task task, TimeSpan timeout)
|
|
{
|
|
using (var cts = new CancellationTokenSource())
|
|
{
|
|
if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)))
|
|
{
|
|
cts.Cancel();
|
|
await task;
|
|
return;
|
|
}
|
|
}
|
|
|
|
throw new TimeoutException();
|
|
}
|
|
}
|
|
} |