Here are the examples of the csharp api System.Threading.CancellationToken.Register(System.Action) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
563 Examples
19
Source : ByteBuffer.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
public ValueTask TakeOutMemoryAsync(Memory<byte> buffer, CancellationToken ct = default)
{
lock (_sync)
{
if (buffer.Length > Length && _maxiumBufferSize >= 0)
{
var source = new _source();
var reg = ct.Register(() =>
{
source.Cancel();
});
Action ac = null;
ac = () =>
{
if (buffer.Length <= Length)
{
_dataWritten -= ac;
reg.Dispose();
TakeOutMemoryNoCheck(buffer.Span);
source.Success();
}
};
_dataWritten += ac;
return new ValueTask(source, 0);
}
}
TakeOutMemoryNoCheck(buffer.Span);
return default;
}
19
Source : IOPipeLine.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
public Task StartAsync(CancellationToken ct = default)
{
var d = PipeOptions.Default;
var opt = new PipeOptions(
d.Pool,
d.ReaderScheduler,
d.WriterScheduler,
_resumeWriterThreshole,
d.ResumeWriterThreshold,
d.MinimumSegmentSize,
d.UseSynchronizationContext);
var pipe = new Pipe(opt);
var t1 = Producer(_socket, pipe.Writer, ct);
var t2 = Consumer(pipe.Reader, ct);
var t3 = Writer(ct);
ct.Register(() =>
{
ChunkStreamContext?.Dispose();
ChunkStreamContext = null;
});
var tcs = new TaskCompletionSource<int>();
Action<Task> setException = t =>
{
tcs.TrySetException(t.Exception.InnerException);
};
Action<Task> setCanceled = _ =>
{
tcs.TrySetCanceled();
};
Action<Task> setResult = t =>
{
tcs.TrySetResult(1);
};
t1.ContinueWith(setException, TaskContinuationOptions.OnlyOnFaulted);
t2.ContinueWith(setException, TaskContinuationOptions.OnlyOnFaulted);
t3.ContinueWith(setException, TaskContinuationOptions.OnlyOnFaulted);
t1.ContinueWith(setCanceled, TaskContinuationOptions.OnlyOnCanceled);
t2.ContinueWith(setCanceled, TaskContinuationOptions.OnlyOnCanceled);
t3.ContinueWith(setCanceled, TaskContinuationOptions.OnlyOnCanceled);
t1.ContinueWith(setResult, TaskContinuationOptions.OnlyOnRanToCompletion);
t2.ContinueWith(setResult, TaskContinuationOptions.OnlyOnRanToCompletion);
t3.ContinueWith(setResult, TaskContinuationOptions.OnlyOnRanToCompletion);
return tcs.Task;
}
19
Source : ProcessInvoker.cs
with MIT License
from actions
with MIT License
from actions
public async Task<int> ExecuteAsync(
string workingDirectory,
string fileName,
string arguments,
IDictionary<string, string> environment,
bool requireExitCodeZero,
Encoding outputEncoding,
bool killProcessOnCancel,
Channel<string> redirectStandardIn,
bool inheritConsoleHandler,
bool keepStandardInOpen,
bool highPriorityProcess,
CancellationToken cancellationToken)
{
ArgUtil.Null(_proc, nameof(_proc));
ArgUtil.NotNullOrEmpty(fileName, nameof(fileName));
Trace.Info("Starting process:");
Trace.Info($" File name: '{fileName}'");
Trace.Info($" Arguments: '{arguments}'");
Trace.Info($" Working directory: '{workingDirectory}'");
Trace.Info($" Require exit code zero: '{requireExitCodeZero}'");
Trace.Info($" Encoding web name: {outputEncoding?.WebName} ; code page: '{outputEncoding?.CodePage}'");
Trace.Info($" Force kill process on cancellation: '{killProcessOnCancel}'");
Trace.Info($" Redirected STDIN: '{redirectStandardIn != null}'");
Trace.Info($" Persist current code page: '{inheritConsoleHandler}'");
Trace.Info($" Keep redirected STDIN open: '{keepStandardInOpen}'");
Trace.Info($" High priority process: '{highPriorityProcess}'");
_proc = new Process();
_proc.StartInfo.FileName = fileName;
_proc.StartInfo.Arguments = arguments;
_proc.StartInfo.WorkingDirectory = workingDirectory;
_proc.StartInfo.UseShellExecute = false;
_proc.StartInfo.CreateNoWindow = !inheritConsoleHandler;
_proc.StartInfo.RedirectStandardInput = true;
_proc.StartInfo.RedirectStandardError = true;
_proc.StartInfo.RedirectStandardOutput = true;
// Ensure we process STDERR even the process exit event happen before we start read STDERR stream.
if (_proc.StartInfo.RedirectStandardError)
{
Interlocked.Increment(ref _asyncStreamReaderCount);
}
// Ensure we process STDOUT even the process exit event happen before we start read STDOUT stream.
if (_proc.StartInfo.RedirectStandardOutput)
{
Interlocked.Increment(ref _asyncStreamReaderCount);
}
#if OS_WINDOWS
// If StandardErrorEncoding or StandardOutputEncoding is not specified the on the
// ProcessStartInfo object, then .NET PInvokes to resolve the default console output
// code page:
// [DllImport("api-ms-win-core-console-l1-1-0.dll", SetLastError = true)]
// public extern static uint GetConsoleOutputCP();
StringUtil.EnsureRegisterEncodings();
#endif
if (outputEncoding != null)
{
_proc.StartInfo.StandardErrorEncoding = outputEncoding;
_proc.StartInfo.StandardOutputEncoding = outputEncoding;
}
// Copy the environment variables.
if (environment != null && environment.Count > 0)
{
foreach (KeyValuePair<string, string> kvp in environment)
{
_proc.StartInfo.Environment[kvp.Key] = kvp.Value;
}
}
// Indicate GitHub Actions process.
_proc.StartInfo.Environment["GITHUB_ACTIONS"] = "true";
// Set CI=true when no one else already set it.
// CI=true is common set in most CI provider in GitHub
if (!_proc.StartInfo.Environment.ContainsKey("CI") &&
Environment.GetEnvironmentVariable("CI") == null)
{
_proc.StartInfo.Environment["CI"] = "true";
}
// Hook up the events.
_proc.EnableRaisingEvents = true;
_proc.Exited += ProcessExitedHandler;
// Start the process.
_stopWatch = Stopwatch.StartNew();
_proc.Start();
// Decrease invoked process priority, in platform specifc way, relative to parent
if (!highPriorityProcess)
{
DecreaseProcessPriority(_proc);
}
// Start the standard error notifications, if appropriate.
if (_proc.StartInfo.RedirectStandardError)
{
StartReadStream(_proc.StandardError, _errorData);
}
// Start the standard output notifications, if appropriate.
if (_proc.StartInfo.RedirectStandardOutput)
{
StartReadStream(_proc.StandardOutput, _outputData);
}
if (_proc.StartInfo.RedirectStandardInput)
{
if (redirectStandardIn != null)
{
StartWriteStream(redirectStandardIn, _proc.StandardInput, keepStandardInOpen);
}
else
{
// Close the input stream. This is done to prevent commands from blocking the build waiting for input from the user.
_proc.StandardInput.Close();
}
}
var cancellationFinished = new TaskCompletionSource<bool>();
using (var registration = cancellationToken.Register(async () =>
{
await CancelAndKillProcessTree(killProcessOnCancel);
cancellationFinished.TrySetResult(true);
}))
{
Trace.Info($"Process started with process id {_proc.Id}, waiting for process exit.");
while (true)
{
Task outputSignal = _outputProcessEvent.WaitAsync();
var signaled = await Task.WhenAny(outputSignal, _processExitedCompletionSource.Task);
if (signaled == outputSignal)
{
ProcessOutput();
}
else
{
_stopWatch.Stop();
break;
}
}
// Just in case there was some pending output when the process shut down go ahead and check the
// data buffers one last time before returning
ProcessOutput();
if (cancellationToken.IsCancellationRequested)
{
// Ensure cancellation also finish on the cancellationToken.Register thread.
await cancellationFinished.Task;
Trace.Info($"Process Cancellation finished.");
}
Trace.Info($"Finished process {_proc.Id} with exit code {_proc.ExitCode}, and elapsed time {_stopWatch.Elapsed}.");
}
cancellationToken.ThrowIfCancellationRequested();
// Wait for process to finish.
if (_proc.ExitCode != 0 && requireExitCodeZero)
{
throw new ProcessExitCodeException(exitCode: _proc.ExitCode, fileName: fileName, arguments: arguments);
}
return _proc.ExitCode;
}
19
Source : TaskCancellationExtensions.cs
with MIT License
from actions
with MIT License
from actions
public static async Task<TResult> EnforceCancellation<TResult>(
this Task<TResult> task,
CancellationToken cancellationToken,
Func<string> makeMessage = null,
[CallerFilePath] string file = "",
[CallerMemberName] string member = "",
[CallerLineNumber] int line = -1)
{
ArgumentUtility.CheckForNull(task, nameof(task));
// IsCompleted will return true when the task is in one of the three final states: RanToCompletion, Faulted, or Canceled.
if (task.IsCompleted)
{
return await task;
}
var cancellationTcs = new TaskCompletionSource<bool>(RUN_CONTINUATIONS_ASYNCHRONOUSLY);
using (cancellationToken.Register(() => cancellationTcs.SetResult(false)))
{
var completedTask = await Task.WhenAny(task, cancellationTcs.Task).ConfigureAwait(false);
if (completedTask == task)
{
return await task;
}
}
// Even if our actual task actually did honor the cancellation token, there's still a race that our WaitForCancellation
// task may have handled the cancellation more quickly.
if (!cancellationToken.IsCancellationRequested)
{
throw new InvalidOperationException("Task ended but cancellation token is not marked for cancellation.");
}
// However, we'd ideally like to throw the cancellation exception from the original task if we can.
// Thus, we'll give that task a few seconds to coallesce (e.g. write to a log) before we give up on it.
int seconds = 3;
var lastChanceTcs = new TaskCompletionSource<bool>(RUN_CONTINUATIONS_ASYNCHRONOUSLY);
using (var lastChanceTimer = new CancellationTokenSource(TimeSpan.FromSeconds(seconds)))
using (lastChanceTimer.Token.Register(() => lastChanceTcs.SetResult(false)))
{
var completedTask = await Task.WhenAny(task, lastChanceTcs.Task).ConfigureAwait(false);
if (completedTask == task)
{
return await task;
}
}
// At this point, we've given up on waiting for this task.
ObserveExceptionIfNeeded(task);
string errorString = $"Task in function {member} at {file}:{line} was still active {seconds} seconds after operation was cancelled.";
if (makeMessage != null)
{
errorString += $" {makeMessage()}";
}
throw new OperationCanceledException(errorString, cancellationToken);
}
19
Source : RpcClient.cs
with MIT License
from ad313
with MIT License
from ad313
public Task<string> CallAsync(string message, CancellationToken cancellationToken = default(CancellationToken))
{
IBasicProperties props = channel.CreateBasicProperties();
var correlationId = Guid.NewGuid().ToString();
props.CorrelationId = correlationId;
props.ReplyTo = replyQueueName;
var messageBytes = Encoding.UTF8.GetBytes(message);
var tcs = new TaskCompletionSource<string>();
callbackMapper.TryAdd(correlationId, tcs);
channel.BasicPublish(
exchange: "",
routingKey: QUEUE_NAME,
basicProperties: props,
body: messageBytes);
channel.BasicConsume(
consumer: consumer,
queue: replyQueueName,
autoAck: true);
cancellationToken.Register(() => callbackMapper.TryRemove(correlationId, out var tmp));
return tcs.Task;
}
19
Source : StreamVideoSource.cs
with MIT License
from adamfisher
with MIT License
from adamfisher
internal async Task<Stream> GetStreamAsync(CancellationToken userToken = default(CancellationToken))
{
Stream result = null;
if (Stream != null)
{
OnLoadingStarted();
userToken.Register(CancellationTokenSource.Cancel);
try
{
result = await Stream(CancellationTokenSource.Token);
OnLoadingCompleted(false);
}
catch (OperationCanceledException)
{
OnLoadingCompleted(true);
throw;
}
}
return result;
}
19
Source : MainForm.cs
with GNU General Public License v3.0
from AdamWhiteHat
with GNU General Public License v3.0
from AdamWhiteHat
private void SetAsProcessing()
{
ControlBridge.SetControlVisibleState(panelCancel, true);
ControlBridge.SetControlVisibleState(panelButtons, false);
_cancellationTokenSource = new CancellationTokenSource();
_cancellationToken = _cancellationTokenSource.Token;
_cancellationToken.Register(new Action(() => RestoreAllButtons()));
Logging.LogMessage($"Processing thread LAUNCHED.");
IsWorking = true;
}
19
Source : InteractionPaginationRequest.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
internal void RegenerateCTS(DiscordInteraction interaction)
{
this._interactionCts?.Dispose();
this._lastInteraction = interaction;
this._interactionCts = new(TimeSpan.FromSeconds((60 * 15) - 5));
this._interactionCts.Token.Register(() => this._tcs.TrySetResult(false));
}
19
Source : CompletableToTask.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
internal void Init(CancellationTokenSource cts)
{
if (cts != null)
{
reg = cts.Token.Register(Dispose);
hasTokenSource = true;
}
}
19
Source : ExportersManager.cs
with MIT License
from akpaevj
with MIT License
from akpaevj
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
stoppingToken.Register(() =>
{
lock (_runExporters)
{
foreach (var ib in _runExporters)
ib.Value.Cancel();
}
});
foreach (var clstFolder in _clstFolders)
{
var clsreplacedcher = new Clsreplacedcher(clstFolder.Folder, clstFolder.Templates);
foreach (var (key, (name, dataBaseName)) in clsreplacedcher.InfoBases)
StartExporter(key, name, dataBaseName);
clsreplacedcher.InfoBasesAdded += Clsreplacedcher_InfoBasesAdded;
clsreplacedcher.InfoBasesDeleted += Clsreplacedcher_InfoBasesDeleted;
_clsreplacedchers.Add(clsreplacedcher);
}
await Task.Factory.StartNew(stoppingToken.WaitHandle.WaitOne, stoppingToken);
}
19
Source : TechLogExporter.cs
with MIT License
from akpaevj
with MIT License
from akpaevj
public async Task StartAsync(CancellationToken cancellationToken = default)
{
_logger?.LogInformation("Exporter is started");
_cancellationToken = cancellationToken;
_cancellationToken.Register(() => _readBlock.Complete());
var logFiles = Directory.GetFiles(_settings.LogFolder, "*.log", SearchOption.AllDirectories);
foreach (var logFile in logFiles)
StartFileReading(logFile);
if (_settings.LiveMode)
InitializeWatcher();
else
_readBlock.Complete();
await _writeBlock.Completion;
_logger?.LogInformation("Exporter is stopped");
}
19
Source : KRequestResponseQueue.cs
with MIT License
from alethic
with MIT License
from alethic
public async Task<KResponse<TNodeId, TResponse>> WaitAsync<TResponse>(TKey key, CancellationToken cancellationToken)
where TResponse : struct, IKResponseBody<TNodeId>
{
using (var cts = new CancellationTokenSource(timeout))
{
// generate a new task completion source hooked up with the given request information
var tcs = queue.GetOrAdd(key, k =>
{
var tcs = new TaskCompletionSource<object>();
var lnk = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token);
lnk.Token.Register(() => { queue.TryRemove(k, out _); tcs.TrySetCanceled(); });
return tcs;
});
try
{
return (KResponse<TNodeId, TResponse>)await tcs.Task;
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
throw new KProtocolException(KProtocolError.EndpointNotAvailable, "Timeout received.");
}
}
}
19
Source : ReliabilityStateMachine.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
public static async Task<T> TryUntilSuccess<T>(Func<Task<T>> action, CancellationToken cancellationToken)
{
var reliabilityMonitor = new ReliabilityStateMachine();
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
var result = await action();
reliabilityMonitor.Succeeded();
return result;
}
catch (Exception)
{
var tcs = new TaskCompletionSource<bool>();
var timer = reliabilityMonitor.GetRetryTimer(() => tcs.SetResult(true));
// Allow cancellation of the timer
cancellationToken.Register(() => tcs.TrySetCanceled());
// Wait for the retry timer to expire
await tcs.Task;
}
}
}
19
Source : NSUrlSessionHandler.cs
with MIT License
from alexrainman
with MIT License
from alexrainman
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var headers = request.Headers as IEnumerable<KeyValuePair<string, IEnumerable<string>>>;
var ms = new MemoryStream();
if (request.Content != null)
{
await request.Content.CopyToAsync(ms).ConfigureAwait(false);
headers = headers.Union(request.Content.Headers).ToArray();
}
// Add Cookie Header if any cookie for the domain in the cookie store
var stringBuilder = new StringBuilder();
var cookies = NSHttpCookieStorage.SharedStorage.Cookies
.Where(c => c.Domain == request.RequestUri.Host)
.Where(c => Utility.PathMatches(request.RequestUri.AbsolutePath, c.Path))
.ToList();
foreach (var cookie in cookies)
{
stringBuilder.Append(cookie.Name + "=" + cookie.Value + ";");
}
var rq = new NSMutableUrlRequest()
{
AllowsCellularAccess = true,
Body = NSData.FromArray(ms.ToArray()),
CachePolicy = (!this.DisableCaching ? NSUrlRequestCachePolicy.UseProtocolCachePolicy : NSUrlRequestCachePolicy.ReloadIgnoringCacheData),
Headers = headers.Aggregate(new NSMutableDictionary(), (acc, x) => {
if (x.Key == "Cookie")
{
foreach (var val in x.Value)
stringBuilder.Append(val + ";");
}
else
{
acc.Add(new NSString(x.Key), new NSString(String.Join(getHeaderSeparator(x.Key), x.Value)));
}
return acc;
}),
HttpMethod = request.Method.ToString().ToUpperInvariant(),
Url = NSUrl.FromString(request.RequestUri.AbsoluteUri),
};
if (stringBuilder.Length > 0)
{
var copy = new NSMutableDictionary(rq.Headers);
copy.Add(new NSString("Cookie"), new NSString(stringBuilder.ToString().TrimEnd(';')));
rq.Headers = copy;
}
if (Timeout != null)
rq.TimeoutInterval = Timeout.Value.TotalSeconds;
var op = session.CreateDataTask(rq);
cancellationToken.ThrowIfCancellationRequested();
var ret = new TaskCompletionSource<HttpResponseMessage>();
cancellationToken.Register(() => ret.TrySetCanceled());
lock (inflightRequests)
{
inflightRequests[op] = new InflightOperation()
{
FutureResponse = ret,
Request = request,
Progress = getAndRemoveCallbackFromRegister(request),
ResponseBody = new ByteArrayListStream(),
CancellationToken = cancellationToken,
};
}
op.Resume();
return await ret.Task.ConfigureAwait(false);
}
19
Source : TcpServer.cs
with MIT License
from alexwahl
with MIT License
from alexwahl
private async Task ListenForClientConnection(CancellationToken ct)
{
this.tcpListener.Start();
ct.Register(CancelComm);
while (!ct.IsCancellationRequested)
{
//blocks until a client has connected to the server
TcpClient client = await this.tcpListener.AcceptTcpClientAsync();
//only one client can connect !
NetworkStream clientStream = client.GetStream();
Connection_established();
byte[] message = new byte[4096];
int bytesRead;
while (!ct.IsCancellationRequested)
{
try
{
bytesRead = 0;
//read message from client
bytesRead = await clientStream.ReadAsync(message, 0, 4096, ct).ConfigureAwait(true);
var str = System.Text.Encoding.Default.GetString(message, 0,bytesRead);
var answer = rigctrl.ExecCommand(str);
var answerBytes = (new System.Text.ASCIIEncoding()).GetBytes(answer);
await clientStream.WriteAsync(answerBytes, 0, answerBytes.Length,ct).ConfigureAwait(true);
}
catch
{
//a socket error has occured
break;
}
}
client.Close();
connection_lost();
}
}
19
Source : VideoAnalyzer.cs
with MIT License
from AlturosDestinations
with MIT License
from AlturosDestinations
public async Task<replacedyzeResult> GetVideoInfoAsync(string videoFilePath, CancellationToken cancellationToken = default)
{
if (!File.Exists(videoFilePath))
{
return new replacedyzeResult { Successful = false, ErrorMessage = "File does not exist" };
}
cancellationToken.Register(() => this.KillProcess());
return await this.GetVideoInfoAsync(new MediaInput { FilePath = videoFilePath }, cancellationToken).ConfigureAwait(false);
}
19
Source : VideoAnalyzer.cs
with MIT License
from AlturosDestinations
with MIT License
from AlturosDestinations
public async Task<replacedyzeResult> GetVideoInfoAsync(byte[] data, CancellationToken cancellationToken = default)
{
cancellationToken.Register(() => this.KillProcess());
return await this.GetVideoInfoAsync(new MediaInput { FileContent = data }, cancellationToken).ConfigureAwait(false);
}
19
Source : DefaultCamundaWorkerTest.cs
with MIT License
from AMalininHere
with MIT License
from AMalininHere
[Fact]
public async Task TestCancelledSelection()
{
var cts = new CancellationTokenSource();
var tcs = new TaskCompletionSource<List<ExternalTask>>();
await using var reg = cts.Token.Register(() => tcs.SetCanceled());
_clientMock
.Setup(client =>
client.FetchAndLockAsync(It.IsAny<FetchAndLockRequest>(), It.IsAny<CancellationToken>()))
.Returns(tcs.Task);
var resultTask = _worker.RunAsync(cts.Token);
cts.Cancel();
await replacedert.ThrowsAsync<TaskCanceledException>(() => resultTask);
_clientMock.VerifyAll();
}
19
Source : InMemoryDatabaseTransaction.cs
with Apache License 2.0
from Anapher
with Apache License 2.0
from Anapher
private ValueTask<T> AddTransactionStep<T>(Func<ValueTask<T>> operation)
{
var waitHandler = new TaskCompletionSource<T>();
async ValueTask Step()
{
var result = await operation();
waitHandler.SetResult(result);
}
_cancellationTokenSource.Token.Register(() => waitHandler.TrySetCanceled());
_transactionSteps.Add(Step);
return new ValueTask<T>(waitHandler.Task);
}
19
Source : ModbusClient.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
private async Task<Response> SendRequest(Request request, CancellationToken cancellationToken)
{
try
{
logger?.LogTrace("ModbusClient.SendRequest enter");
CheckDisposed();
lock (reconnectLock)
{
if (!IsConnected)
{
if (!isReconnecting)
ConnectingTask = GetReconnectTask(true);
throw new InvalidOperationException("Modbus client is not connected.");
}
}
var task = new RequestTask
{
Request = request,
TaskCompletionSource = new TaskCompletionSource<Response>()
};
task.Registration = cancellationToken.Register(() => RemoveTask(task));
lock (queueLock)
{
sendQueue.Add(task);
}
return await task.TaskCompletionSource.Task;
}
catch (Exception ex)
{
logger?.LogError(ex, $"Enqueueing request failed: {ex.GetMessage()}");
return new Response(new byte[] { 0, 0, 0, 0, 0, 0 });
}
finally
{
logger?.LogTrace("ModbusClient.SendRequest leave");
}
}
19
Source : ModbusClient.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
private async Task Reconnect()
{
try
{
logger?.LogTrace("ModbusClient.Reconnect enter");
lock (reconnectLock)
{
if (isReconnecting || stopCts.IsCancellationRequested)
return;
isReconnecting = true;
IsConnected = false;
}
logger?.LogInformation($"{(wasConnected ? "Reconnect" : "Connect")} starting.");
if (wasConnected)
Task.Run(() => Disconnected?.Invoke(this, EventArgs.Empty)).Forget();
sendCts?.Cancel();
await sendTask;
sendCts = null;
int timeout = 2;
int maxTimeout = 30;
var startTime = DateTime.UtcNow;
using (stopCts.Token.Register(() => reconnectTcs.TrySetCanceled()))
{
while (!stopCts.IsCancellationRequested)
{
try
{
serialPort?.Dispose();
serialPort = new SerialPort(PortName)
{
BaudRate = (int)BaudRate,
DataBits = DataBits,
Parity = Parity,
StopBits = StopBits,
Handshake = Handshake,
ReadTimeout = (int)ReceiveTimeout.TotalMilliseconds,
WriteTimeout = (int)SendTimeout.TotalMilliseconds
};
if (bufferSize > 0)
{
serialPort.ReadBufferSize = bufferSize;
serialPort.WriteBufferSize = bufferSize;
}
var task = Task.Run(() => serialPort.Open());
if (await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(timeout), stopCts.Token)) == task)
{
if (serialPort.IsOpen)
{
lock (reconnectLock)
{
IsConnected = true;
wasConnected = true;
reconnectTcs?.TrySetResult(true);
Task.Run(() => Connected?.Invoke(this, EventArgs.Empty)).Forget();
}
logger?.LogInformation($"{(wasConnected ? "Reconnect" : "Connect")}ed successfully.");
sendCts = new CancellationTokenSource();
sendTask = Task.Run(async () => await ProcessSendQueue());
return;
}
else
{
logger?.LogError($"{(wasConnected ? "Reconnect" : "Connect")} failed: Could not open serial port {serialPort.PortName}.");
reconnectTcs?.TrySetException((Exception)task.Exception ?? new IOException("Serial port not opened."));
return;
}
}
else if (stopCts.IsCancellationRequested)
{
logger?.LogInformation($"{(wasConnected ? "Reconnect" : "Connect")} cancelled.");
return;
}
else
{
logger?.LogWarning($"{(wasConnected ? "Reconnect" : "Connect")} failed within {timeout} seconds.");
timeout += 2;
if (timeout > maxTimeout)
timeout = maxTimeout;
throw new IOException();
}
}
catch (IOException) when (ReconnectTimeSpan == TimeSpan.MaxValue || DateTime.UtcNow <= startTime + ReconnectTimeSpan)
{
await Task.Delay(1000, stopCts.Token);
continue;
}
catch (Exception ex)
{
logger?.LogError(ex, "ModbusClient.Reconnect failed");
reconnectTcs?.TrySetException(ex);
return;
}
}
}
}
catch (OperationCanceledException) when (stopCts.IsCancellationRequested)
{
// Client shutting down
return;
}
finally
{
lock (reconnectLock)
{
isReconnecting = false;
reconnectTcs = null;
}
logger?.LogTrace("ModbusClient.Reconnect leave");
}
}
19
Source : ModbusServer.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
private async Task HandleClient(TcpClient client)
{
logger?.LogTrace("ModbusServer.HandleClient enter");
var endpoint = (IPEndPoint)client.Client.RemoteEndPoint;
try
{
ClientConnected?.Invoke(this, new ClientEventArgs(endpoint));
logger?.LogInformation($"Client connected: {endpoint.Address}.");
var stream = client.GetStream();
while (!stopCts.IsCancellationRequested)
{
using var requestStream = new MemoryStream();
using (var cts = new CancellationTokenSource(Timeout))
using (stopCts.Token.Register(() => cts.Cancel()))
{
try
{
byte[] header = await stream.ReadExpectedBytes(6, cts.Token);
await requestStream.WriteAsync(header, 0, header.Length, cts.Token);
byte[] bytes = header.Skip(4).Take(2).ToArray();
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
int following = BitConverter.ToUInt16(bytes, 0);
byte[] payload = await stream.ReadExpectedBytes(following, cts.Token);
await requestStream.WriteAsync(payload, 0, payload.Length, cts.Token);
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
continue;
}
}
try
{
var request = new Request(requestStream.GetBuffer());
var response = requestHandler?.Invoke(request, stopCts.Token);
if (response != null)
{
using var cts = new CancellationTokenSource(Timeout);
using var reg = stopCts.Token.Register(() => cts.Cancel());
try
{
byte[] bytes = response.Serialize();
await stream.WriteAsync(bytes, 0, bytes.Length, cts.Token);
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
continue;
}
}
}
catch (ArgumentException ex)
{
logger?.LogWarning(ex, $"Invalid data received from {endpoint.Address}: {ex.Message}");
}
catch (NotImplementedException ex)
{
logger?.LogWarning(ex, $"Invalid data received from {endpoint.Address}: {ex.Message}");
}
}
}
catch (IOException)
{
// client connection closed
return;
}
catch (Exception ex)
{
logger?.LogError(ex, $"Unexpected error ({ex.GetType().Name}) occurred: {ex.GetMessage()}");
}
finally
{
ClientDisconnected?.Invoke(this, new ClientEventArgs(endpoint));
logger?.LogInformation($"Client disconnected: {endpoint.Address}");
client.Dispose();
tcpClients.TryRemove(client, out _);
logger?.LogTrace("ModbusServer.HandleClient leave");
}
}
19
Source : Extensions.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public static async Task<int> ReadAsync(this SerialPort serialPort, byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// serial port read/write timeouts seem to be ignored, so ensure the timeouts.
using (var cts = new CancellationTokenSource(serialPort.ReadTimeout))
using (cancellationToken.Register(() => cts.Cancel()))
{
var ctr = default(CancellationTokenRegistration);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// The async stream implementation on windows is a bit broken.
// this kicks it back to us.
ctr = cts.Token.Register(() => serialPort.DiscardInBuffer());
}
try
{
return await serialPort.BaseStream.ReadAsync(buffer, offset, count, cts.Token);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
cancellationToken.ThrowIfCancellationRequested();
return 0;
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
throw new TimeoutException("No bytes to read within the ReadTimeout.");
}
catch (IOException) when (cts.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
throw new TimeoutException("No bytes to read within the ReadTimeout.");
}
finally
{
ctr.Dispose();
}
}
}
19
Source : Extensions.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public static async Task WriteAsync(this SerialPort serialPort, byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// serial port read/write timeouts seem to be ignored, so ensure the timeouts.
using (var cts = new CancellationTokenSource(serialPort.WriteTimeout))
using (cancellationToken.Register(() => cts.Cancel()))
{
var ctr = default(CancellationTokenRegistration);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// The async stream implementation on windows is a bit broken.
// this kicks it back to us.
ctr = cts.Token.Register(() => serialPort.DiscardOutBuffer());
}
try
{
await serialPort.BaseStream.WriteAsync(buffer, offset, count, cts.Token);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
cancellationToken.ThrowIfCancellationRequested();
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
throw new TimeoutException("No bytes written within the WriteTimeout.");
}
catch (IOException) when (cts.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
throw new TimeoutException("No bytes written within the WriteTimeout.");
}
finally
{
ctr.Dispose();
}
}
}
19
Source : AsyncSequence.cs
with MIT License
from Andrew-Hanlon
with MIT License
from Andrew-Hanlon
public async Task<bool> MoveNextAsync(CancellationToken cancellationToken)
{
_exception?.Throw();
if (_valueQueue.TryDequeue(out var value))
{
Current = value;
return true;
}
if (IsCompleted)
return false;
_nextSource = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() => _nextSource.TrySetCanceled()))
{
await _nextSource.Task;
}
if (!_valueQueue.TryDequeue(out value))
return !IsCompleted;
Current = value;
return true;
}
19
Source : TemplateProcessor.cs
with MIT License
from andyalm
with MIT License
from andyalm
public Task RunAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var completionSource = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
var consulDependencies = _renderer.replacedyzeDependencies(TemplatePath, Properties);
var subscription = _client.ObserveDependencies(consulDependencies).Subscribe(consulState =>
{
ConsulState = consulState;
RenderTemplate();
}, onError: exception =>
{
completionSource.SetException(exception);
}, onCompleted: () =>
{
completionSource.SetResult(null);
});
cancellationToken.Register(() => subscription.Dispose());
return completionSource.Task;
}
19
Source : GracePeriodManagerTask.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogDebug("GracePeriodManagerService is starting.");
stoppingToken.Register(() => _logger.LogDebug("#1 GracePeriodManagerService background task is stopping."));
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogDebug("GracePeriodManagerService background task is doing background work.");
CheckConfirmedGracePeriodOrders();
await Task.Delay(_settings.CheckUpdateTime, stoppingToken);
}
_logger.LogDebug("GracePeriodManagerService background task is stopping.");
await Task.CompletedTask;
}
19
Source : WaitOperationManager.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public async Task<T> GetResult(CancellationToken ct = default)
{
CheckDisposed();
if (ct.CanBeCanceled)
{
ct.Register(() =>
{
_tcs.SetCanceled();
});
}
try
{
return await _tcs.Task;
}
finally
{
Dispose();
}
}
19
Source : WaitOperationManager.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public async Task WaitForCompletion(CancellationToken ct = default)
{
CheckDisposed();
if (ct.CanBeCanceled)
{
ct.Register(() =>
{
_tcs.SetCanceled();
});
}
try
{
await _tcs.Task;
}
finally
{
Dispose();
}
}
19
Source : FailoverRequest.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public void ScheduleTimeout()
{
if (cancellationTokenSource == null && requestTimeout != NmsConnectionInfo.INFINITE)
{
TimeSpan timeout = TimeSpan.FromMilliseconds(requestTimeout) - (DateTime.UtcNow - requestStarted);
if (timeout > TimeSpan.Zero)
{
cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(requestTimeout));
cancellationTokenSource.Token.Register(ExpireTask);
}
else
{
ExpireTask();
}
}
}
19
Source : CancelableCompletionSource.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public void SetupCancellation(Action callback, CancellationToken token)
=> _registration = token.Register(callback);
19
Source : FakeSerialPort.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn
with GNU Lesser General Public License v3.0
from Apollo3zehn
public async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken token)
{
if (!this.IsOpen)
throw new Exception("This method is only available when the port is open.");
var registration = token.Register(() =>
{
_length = 0;
_autoResetEvent.Set();
});
await Task.Run(() => this.Read(buffer, offset, count), token);
registration.Dispose();
if (_length == 0)
throw new TaskCanceledException();
return _length;
}
19
Source : JobManagerImpl.cs
with MIT License
from aritchie
with MIT License
from aritchie
public override async Task<JobRunResult> Run(string jobName, CancellationToken cancelToken)
{
using (var cancelSrc = new CancellationTokenSource())
{
using (cancelToken.Register(() => cancelSrc.Cancel()))
{
var app = UIApplication.SharedApplication;
var taskId = (int) app.BeginBackgroundTask(jobName, cancelSrc.Cancel);
var result = await base.Run(jobName, cancelSrc.Token);
app.EndBackgroundTask(taskId);
return result;
}
}
}
19
Source : JobManagerImpl.cs
with MIT License
from aritchie
with MIT License
from aritchie
public override async Task<IEnumerable<JobRunResult>> RunAll(CancellationToken cancelToken)
{
using (var cancelSrc = new CancellationTokenSource())
{
using (cancelToken.Register(() => cancelSrc.Cancel()))
{
var app = UIApplication.SharedApplication;
var taskId = (int) app.BeginBackgroundTask("RunAll", cancelSrc.Cancel);
var result = await base.RunAll(cancelSrc.Token);
app.EndBackgroundTask(taskId);
return result;
}
}
}
19
Source : StreamVideoSource.cs
with MIT License
from arqueror
with MIT License
from arqueror
internal async Task<Stream> GetStreamAsync(CancellationToken userToken = default(CancellationToken))
{
Stream result = null;
if (Stream != null)
{
OnLoadingStarted();
userToken.Register(CancellationTokenSource.Cancel);
try
{
result = await Stream(CancellationTokenSource.Token);
OnLoadingCompleted(false);
}
catch (OperationCanceledException)
{
OnLoadingCompleted(true);
throw;
}
}
return result;
}
19
Source : DiscordExtensions.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public static Task WaitForReadyAsync(this DiscordSocketClient client, CancellationToken ct)
{
var readyTaskSource = new TaskCompletionSource<bool>();
ct.Register(() => readyTaskSource.TrySetCanceled());
client.Ready += () =>
{
readyTaskSource.SetResult(true);
return Task.CompletedTask;
};
return readyTaskSource.Task;
}
19
Source : DiscordExtensions.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public static Task WaitForReadyAsync(this DiscordShardedClient client, CancellationToken ct)
{
var readyTaskSource = new TaskCompletionSource<bool>();
ct.Register(() => readyTaskSource.TrySetCanceled());
var readyClients = new HashSet<DiscordSocketClient>();
client.ShardReady += x =>
{
readyClients.Add(x);
if (readyClients.Count >= client.Shards.Count)
readyTaskSource.TrySetResult(true);
return Task.CompletedTask;
};
return readyTaskSource.Task;
}
19
Source : OwinClientHandler.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
var state = new RequestState(request, cancellationToken);
HttpContent requestContent = request.Content ?? new StreamContent(Stream.Null);
Stream body = await requestContent.ReadreplacedtreamAsync();
if (body.CanSeek)
{
// This body may have been consumed before, rewind it.
body.Seek(0, SeekOrigin.Begin);
}
state.OwinContext.Request.Body = body;
CancellationTokenRegistration registration = cancellationToken.Register(state.Abort);
// Async offload, don't let the test code block the caller.
Task offload = Task.Factory.StartNew(async () =>
{
try
{
await _next(state.Environment);
state.CompleteResponse();
}
catch (Exception ex)
{
state.Abort(ex);
}
finally
{
registration.Dispose();
state.Dispose();
}
});
return await state.ResponseTask;
}
19
Source : ResponseStream.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public async override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
VerifyBuffer(buffer, offset, count, allowEmpty: false);
CancellationTokenRegistration registration = cancellationToken.Register(Abort);
await _readLock.WaitAsync(cancellationToken);
try
{
int totalRead = 0;
do
{
// Don't drained buffered data on abort.
CheckAborted();
if (_topBuffer.Count <= 0)
{
byte[] topBuffer = null;
while (!_bufferedData.TryDequeue(out topBuffer))
{
if (_disposed)
{
CheckAborted();
// Graceful close
return totalRead;
}
await WaitForDataAsync();
}
_topBuffer = new ArraySegment<byte>(topBuffer);
}
int actualCount = Math.Min(count, _topBuffer.Count);
Buffer.BlockCopy(_topBuffer.Array, _topBuffer.Offset, buffer, offset, actualCount);
_topBuffer = new ArraySegment<byte>(_topBuffer.Array,
_topBuffer.Offset + actualCount,
_topBuffer.Count - actualCount);
totalRead += actualCount;
offset += actualCount;
count -= actualCount;
}
while (count > 0 && (_topBuffer.Count > 0 || _bufferedData.Count > 0));
// Keep reading while there is more data available and we have more space to put it in.
return totalRead;
}
finally
{
registration.Dispose();
_readLock.Release();
}
}
19
Source : OwinHttpListenerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void Disconnect_ClientDisconnects_EventFires()
{
var requestReceived = new ManualResetEvent(false);
var requestCanceled = new ManualResetEvent(false);
OwinHttpListener listener = CreateServer(
async env =>
{
GetCallCancelled(env).Register(() => requestCanceled.Set());
requestReceived.Set();
replacedert.True(requestCanceled.WaitOne(1000));
},
HttpServerAddress);
using (listener)
{
var client = new HttpClient();
var requestTask = client.GetAsync(HttpClientAddress);
replacedert.True(requestReceived.WaitOne(1000));
client.CancelPendingRequests();
replacedert.True(requestCanceled.WaitOne(1000));
replacedert.Throws<AggregateException>(() => requestTask.Result);
}
}
19
Source : OwinHttpListenerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void Disconnect_ClientDisconnects_Before_CancellationToken_Created()
{
var requestReceived = new ManualResetEvent(false);
var requestCanceled = new ManualResetEvent(false);
var clientDisposed = new ManualResetEvent(false);
OwinHttpListener listener = CreateServer(
env =>
{
requestReceived.Set();
// lets wait for client to be gone
replacedert.True(clientDisposed.WaitOne(1000));
// the most important part is not to observe CancellationToken before client disconnects
GetCallCancelled(env).Register(() => requestCanceled.Set());
return Task.FromResult(0);
},
HttpServerAddress);
using (listener)
{
using (var client = new HttpClient())
{
var requestTask = client.GetAsync(HttpClientAddress);
replacedert.True(requestReceived.WaitOne(1000));
client.CancelPendingRequests();
replacedert.Throws<AggregateException>(() => requestTask.Result);
}
clientDisposed.Set();
replacedert.True(requestCanceled.WaitOne(1000));
}
}
19
Source : TestBase.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
private int RunWebServerViaEngine(string serverName, string applicationName, string configFileName, bool https)
{
int port = GetAvailablePort(https);
string scheme = https ? "https" : "http";
string sourceDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
string targetDirectory = BuildTargetDirectory(
sourceDirectory,
configFileName,
applicationName,
scheme,
port);
Directory.SetCurrentDirectory(targetDirectory);
var options = new StartOptions(scheme + "://localhost:" + port + "/")
{
ServerFactory = serverName,
AppStartup = applicationName,
};
options.Settings["boot"] = "Domain";
IDisposable server = WebApp.Start(options);
_disposing.Token.Register(() =>
{
server.Dispose();
try
{
Directory.Delete(targetDirectory, true);
}
catch (Exception ex)
{
Trace.WriteLine(string.Format("Cleanup error {0}", ex.Message));
}
});
return port;
}
19
Source : TestBase.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
private int RunWebServerSystemWeb(string applicationName, string configFileName, bool https)
{
var tcs = new TaskCompletionSource<object>();
int port = GetAvailablePort(https);
string sourceDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
string targetDirectory = BuildTargetDirectory(
sourceDirectory,
configFileName,
applicationName,
https ? "https" : "http",
port);
Directory.SetCurrentDirectory(targetDirectory);
string targetHostConfig = Path.Combine(targetDirectory, "ApplicationHost.config");
string programFile32 = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
string iisExpressExe = Path.Combine(programFile32, "IIS Express", "iisexpress.exe");
var info = new ProcessStartInfo
{
WorkingDirectory = targetDirectory,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
ErrorDialog = false,
CreateNoWindow = false,
FileName = iisExpressExe,
Arguments = "/config:\"" + targetHostConfig + "\" /trace:error",
};
// Log.Debug("Executing {0}", Definition.Command);
Process process = Process.Start(info);
process.OutputDataReceived += OutputDataReceived;
process.ErrorDataReceived += OutputDataReceived;
process.Exited += (a, b) => tcs.TrySetResult(null);
process.EnableRaisingEvents = true;
process.BeginOutputReadLine();
process.BeginErrorReadLine();
_disposing.Token.Register(() =>
{
tcs.Task.Wait(250);
if (!process.HasExited)
{
process.Kill();
tcs.Task.Wait();
}
try
{
Directory.Delete(targetDirectory, true);
}
catch (Exception ex)
{
Trace.WriteLine(string.Format("Cleanup error {0}", ex.Message));
}
});
// Wait for the server to get started.
Thread.Sleep(1000);
return port;
}
19
Source : OwinHttpListenerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task AppDelegate_ReturnsExceptionAsync_500Error()
{
bool callCancelled = false;
OwinHttpListener listener = CreateServer(
async env =>
{
GetCallCancelled(env).Register(() => callCancelled = true);
await Task.Delay(1);
throw new NotImplementedException();
},
HttpServerAddress);
HttpResponseMessage response = await SendGetRequest(listener, HttpClientAddress);
replacedert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal(0, response.Content.Headers.ContentLength.Value);
replacedert.True(callCancelled);
}
19
Source : OwinHttpListenerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task Body_PostEcreplacedquest_Success()
{
bool callCancelled = false;
OwinHttpListener listener = CreateServer(
async env =>
{
GetCallCancelled(env).Register(() => callCancelled = true);
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
responseHeaders.Add("Content-Length", requestHeaders["Content-Length"]);
var requestStream = env.Get<Stream>("owin.RequestBody");
var responseStream = env.Get<Stream>("owin.ResponseBody");
var buffer = new MemoryStream();
await requestStream.CopyToAsync(buffer, 1024);
buffer.Seek(0, SeekOrigin.Begin);
await buffer.CopyToAsync(responseStream, 1024);
},
HttpServerAddress);
using (listener)
{
var client = new HttpClient();
string dataString = "Hello World";
HttpResponseMessage result = await client.PostAsync(HttpClientAddress, new StringContent(dataString));
result.EnsureSuccessStatusCode();
replacedert.Equal(dataString.Length, result.Content.Headers.ContentLength.Value);
replacedert.Equal(dataString, await result.Content.ReadreplacedtringAsync());
replacedert.False(callCancelled);
}
}
19
Source : OwinHttpListenerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void BodyDelegate_ThrowsSync_ConnectionClosed()
{
bool callCancelled = false;
OwinHttpListener listener = CreateServer(
env =>
{
GetCallCancelled(env).Register(() => callCancelled = true);
var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
responseHeaders.Add("Content-Length", new string[] { "10" });
var responseStream = env.Get<Stream>("owin.ResponseBody");
responseStream.WriteByte(0xFF);
throw new NotImplementedException();
},
HttpServerAddress);
try
{
// TODO: XUnit 2.0 adds support for replacedert.Throws<...>(async () => await myTask);
// that way we can specify the correct exception type.
replacedert.Throws<AggregateException>(() => SendGetRequest(listener, HttpClientAddress).Result);
}
finally
{
replacedert.True(callCancelled);
}
}
19
Source : OwinHttpListenerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void BodyDelegate_ThrowsAsync_ConnectionClosed()
{
bool callCancelled = false;
OwinHttpListener listener = CreateServer(
env =>
{
GetCallCancelled(env).Register(() => callCancelled = true);
var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
responseHeaders.Add("Content-Length", new string[] { "10" });
var responseStream = env.Get<Stream>("owin.ResponseBody");
responseStream.WriteByte(0xFF);
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
tcs.TrySetException(new NotImplementedException());
return tcs.Task;
},
HttpServerAddress);
try
{
replacedert.Throws<AggregateException>(() => SendGetRequest(listener, HttpClientAddress).Result);
}
finally
{
replacedert.True(callCancelled);
}
}
19
Source : AwaitableSocket.cs
with MIT License
from aspnet
with MIT License
from aspnet
public AwaitableSocket ConnectAsync(CancellationToken cancellationToken)
{
Reset();
if (!_socket.ConnectAsync(_socketAsyncEventArgs))
{
IsCompleted = true;
}
cancellationToken.Register(Cancel);
void Cancel()
{
if (!_socket.Connected)
{
_socket.Dispose();
}
}
return this;
}
19
Source : FutureBatch.cs
with Apache License 2.0
from asynkron
with Apache License 2.0
from asynkron
public async Task<object> GetTask(CancellationToken cancellationToken)
{
try
{
if (cancellationToken == default)
{
return await Tcs.Task;
}
await using (cancellationToken.Register(() => Tcs.TrySetCanceled()))
{
return await Tcs.Task;
}
}
catch
{
_onTimeout?.Invoke();
throw new TimeoutException("Request didn't receive any Response within the expected time.");
}
}
19
Source : Futures.cs
with Apache License 2.0
from asynkron
with Apache License 2.0
from asynkron
public async Task<object> GetTask(CancellationToken cancellationToken)
{
try
{
if (cancellationToken == default)
{
return await _tcs.Task;
}
await using (cancellationToken.Register(() => _tcs.TrySetCanceled()))
{
return await _tcs.Task;
}
}
catch
{
if (!System.Metrics.IsNoop)
{
_metrics!.FuturesTimedOutCount.Inc(new[] {System.Id, System.Address});
}
Stop(Pid);
throw new TimeoutException("Request didn't receive any Response within the expected time.");
}
}
See More Examples