Here are the examples of the csharp api System.Threading.Tasks.Task.WhenAny(params System.Threading.Tasks.Task[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
775 Examples
19
Source : _net40.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout, string message = "The operation has timed out.")
{
using (var timeoutCancellationTokenSource = new CancellationTokenSource())
{
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
if (completedTask == task)
{
timeoutCancellationTokenSource.Cancel();
return await task;
}
else
{
throw new TimeoutException(message);
}
}
}
19
Source : _net40.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static async Task TimeoutAfter(this Task task, TimeSpan timeout, string message = "The operation has timed out.")
{
using (var timeoutCancellationTokenSource = new CancellationTokenSource())
{
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
if (completedTask == task)
{
timeoutCancellationTokenSource.Cancel();
await task;
}
else
{
throw new TimeoutException(message);
}
}
}
19
Source : Utils.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
public static async Task<TResult> WaitAsync<TResult>(this Task<TResult> task, TimeSpan timeout)
{
using var timeoutCancellationTokenSource = new CancellationTokenSource();
var delayTask = Task.Delay(timeout, timeoutCancellationTokenSource.Token);
if (await Task.WhenAny(task, delayTask) == task)
{
timeoutCancellationTokenSource.Cancel();
return await task;
}
throw new TimeoutException("The operation has timed out.");
}
19
Source : ModuleManager.cs
with MIT License
from acid-chicken
with MIT License
from acid-chicken
public static Task<IEnumerable<ModuleInfo>> InstallAsync()
{
DiscordClient.MessageReceived += (message) => Task.WhenAny(HandleCommandAsync(message), Task.Delay(0));
return Service.AddModulesAsync(replacedembly.GetEntryreplacedembly());
}
19
Source : Program.cs
with MIT License
from acid-chicken
with MIT License
from acid-chicken
public static async Task RequestLogAsync(LogMessage message)
{
await Task.WhenAny
(
LogAsync(message),
Task.Delay(0)
).ConfigureAwait(false);
}
19
Source : Extensions.cs
with MIT License
from actions
with MIT License
from actions
public static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(
s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
if (task != await Task.WhenAny(task, tcs.Task))
throw new OperationCanceledException(cancellationToken);
return await task;
}
19
Source : Extensions.cs
with MIT License
from actions
with MIT License
from actions
public static async Task WithCancellation(this Task task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(
s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
if (task != await Task.WhenAny(task, tcs.Task))
throw new OperationCanceledException(cancellationToken);
await task;
}
19
Source : FileContainerServer.cs
with MIT License
from actions
with MIT License
from actions
private async Task UploadReportingAsync(RunnerActionPluginExecutionContext context, int totalFiles, CancellationToken token)
{
int traceInterval = 0;
while (!_uploadFinished.Task.IsCompleted && !token.IsCancellationRequested)
{
bool hasDetailProgress = false;
foreach (var file in _fileUploadProgressLog)
{
string message;
while (file.Value.TryDequeue(out message))
{
hasDetailProgress = true;
context.Output(message);
}
}
// trace total file progress every 25 seconds when there is no file level detail progress
if (++traceInterval % 2 == 0 && !hasDetailProgress)
{
context.Output($"Total file: {totalFiles} ---- Processed file: {_uploadFilesProcessed} ({(_uploadFilesProcessed * 100) / totalFiles}%)");
}
await Task.WhenAny(_uploadFinished.Task, Task.Delay(5000, token));
}
}
19
Source : Runner.cs
with MIT License
from actions
with MIT License
from actions
private async Task<int> RunAsync(RunnerSettings settings, bool runOnce = false)
{
try
{
Trace.Info(nameof(RunAsync));
_listener = HostContext.GetService<IMessageListener>();
if (!await _listener.CreateSessionAsync(HostContext.RunnerShutdownToken))
{
return Constants.Runner.ReturnCode.TerminatedError;
}
HostContext.WritePerfCounter("SessionCreated");
_term.WriteLine($"Current runner version: '{BuildConstants.RunnerPackage.Version}'");
_term.WriteLine($"{DateTime.UtcNow:u}: Listening for Jobs");
IJobDispatcher jobDispatcher = null;
CancellationTokenSource messageQueueLoopTokenSource = CancellationTokenSource.CreateLinkedTokenSource(HostContext.RunnerShutdownToken);
// Should we try to cleanup ephemeral runners
bool runOnceJobCompleted = false;
try
{
var notification = HostContext.GetService<IJobNotification>();
notification.StartClient(settings.MonitorSocketAddress);
bool autoUpdateInProgress = false;
Task<bool> selfUpdateTask = null;
bool runOnceJobReceived = false;
jobDispatcher = HostContext.CreateService<IJobDispatcher>();
while (!HostContext.RunnerShutdownToken.IsCancellationRequested)
{
TaskAgentMessage message = null;
bool skipMessageDeletion = false;
try
{
Task<TaskAgentMessage> getNextMessage = _listener.GetNextMessageAsync(messageQueueLoopTokenSource.Token);
if (autoUpdateInProgress)
{
Trace.Verbose("Auto update task running at backend, waiting for getNextMessage or selfUpdateTask to finish.");
Task completeTask = await Task.WhenAny(getNextMessage, selfUpdateTask);
if (completeTask == selfUpdateTask)
{
autoUpdateInProgress = false;
if (await selfUpdateTask)
{
Trace.Info("Auto update task finished at backend, an runner update is ready to apply exit the current runner instance.");
Trace.Info("Stop message queue looping.");
messageQueueLoopTokenSource.Cancel();
try
{
await getNextMessage;
}
catch (Exception ex)
{
Trace.Info($"Ignore any exception after cancel message loop. {ex}");
}
if (runOnce)
{
return Constants.Runner.ReturnCode.RunOnceRunnerUpdating;
}
else
{
return Constants.Runner.ReturnCode.RunnerUpdating;
}
}
else
{
Trace.Info("Auto update task finished at backend, there is no available runner update needs to apply, continue message queue looping.");
}
}
}
if (runOnceJobReceived)
{
Trace.Verbose("One time used runner has start running its job, waiting for getNextMessage or the job to finish.");
Task completeTask = await Task.WhenAny(getNextMessage, jobDispatcher.RunOnceJobCompleted.Task);
if (completeTask == jobDispatcher.RunOnceJobCompleted.Task)
{
runOnceJobCompleted = true;
Trace.Info("Job has finished at backend, the runner will exit since it is running under onetime use mode.");
Trace.Info("Stop message queue looping.");
messageQueueLoopTokenSource.Cancel();
try
{
await getNextMessage;
}
catch (Exception ex)
{
Trace.Info($"Ignore any exception after cancel message loop. {ex}");
}
return Constants.Runner.ReturnCode.Success;
}
}
message = await getNextMessage; //get next message
HostContext.WritePerfCounter($"MessageReceived_{message.MessageType}");
if (string.Equals(message.MessageType, AgentRefreshMessage.MessageType, StringComparison.OrdinalIgnoreCase))
{
if (autoUpdateInProgress == false)
{
autoUpdateInProgress = true;
var runnerUpdateMessage = JsonUtility.FromString<AgentRefreshMessage>(message.Body);
var selfUpdater = HostContext.GetService<ISelfUpdater>();
selfUpdateTask = selfUpdater.SelfUpdate(runnerUpdateMessage, jobDispatcher, !runOnce && HostContext.StartupType != StartupType.Service, HostContext.RunnerShutdownToken);
Trace.Info("Refresh message received, kick-off selfupdate background process.");
}
else
{
Trace.Info("Refresh message received, skip autoupdate since a previous autoupdate is already running.");
}
}
else if (string.Equals(message.MessageType, JobRequestMessageTypes.PipelineAgentJobRequest, StringComparison.OrdinalIgnoreCase))
{
if (autoUpdateInProgress || runOnceJobReceived)
{
skipMessageDeletion = true;
Trace.Info($"Skip message deletion for job request message '{message.MessageId}'.");
}
else
{
var jobMessage = StringUtil.ConvertFromJson<Pipelines.AgentJobRequestMessage>(message.Body);
jobDispatcher.Run(jobMessage, runOnce);
if (runOnce)
{
Trace.Info("One time used runner received job message.");
runOnceJobReceived = true;
}
}
}
else if (string.Equals(message.MessageType, JobCancelMessage.MessageType, StringComparison.OrdinalIgnoreCase))
{
var cancelJobMessage = JsonUtility.FromString<JobCancelMessage>(message.Body);
bool jobCancelled = jobDispatcher.Cancel(cancelJobMessage);
skipMessageDeletion = (autoUpdateInProgress || runOnceJobReceived) && !jobCancelled;
if (skipMessageDeletion)
{
Trace.Info($"Skip message deletion for cancellation message '{message.MessageId}'.");
}
}
else
{
Trace.Error($"Received message {message.MessageId} with unsupported message type {message.MessageType}.");
}
}
finally
{
if (!skipMessageDeletion && message != null)
{
try
{
await _listener.DeleteMessageAsync(message);
}
catch (Exception ex)
{
Trace.Error($"Catch exception during delete message from message queue. message id: {message.MessageId}");
Trace.Error(ex);
}
finally
{
message = null;
}
}
}
}
}
finally
{
if (jobDispatcher != null)
{
await jobDispatcher.ShutdownAsync();
}
try
{
await _listener.DeleteSessionAsync();
}
catch (Exception ex) when (runOnce)
{
// ignore exception during delete session for ephemeral runner since the runner might already be deleted from the server side
// and the delete session call will ends up with 401.
Trace.Info($"Ignore any exception during DeleteSession for an ephemeral runner. {ex}");
}
messageQueueLoopTokenSource.Dispose();
if (settings.Ephemeral && runOnceJobCompleted)
{
var configManager = HostContext.GetService<IConfigurationManager>();
configManager.DeleteLocalRunnerConfig();
}
}
}
catch (TaskAgentAccessTokenExpiredException)
{
Trace.Info("Runner OAuth token has been revoked. Shutting down.");
}
return Constants.Runner.ReturnCode.Success;
}
19
Source : FileContainerServer.cs
with MIT License
from actions
with MIT License
from actions
private async Task DownloadReportingAsync(RunnerActionPluginExecutionContext context, int totalFiles, CancellationToken token)
{
int traceInterval = 0;
while (!_downloadFinished.Task.IsCompleted && !token.IsCancellationRequested)
{
// trace total file progress every 10 seconds when there is no file level detail progress
if (++traceInterval % 2 == 0)
{
context.Output($"Total file: {totalFiles} ---- Downloaded file: {_downloadFilesProcessed} ({(_downloadFilesProcessed * 100) / totalFiles}%)");
}
await Task.WhenAny(_downloadFinished.Task, Task.Delay(5000, token));
}
}
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 : ProcessInvoker.cs
with MIT License
from actions
with MIT License
from actions
private async Task<bool> SendSignal(Signals signal, TimeSpan timeout)
{
Trace.Info($"Sending {signal} to process {_proc.Id}.");
int errorCode = kill(_proc.Id, (int)signal);
if (errorCode != 0)
{
Trace.Info($"{signal} signal doesn't fire successfully.");
Trace.Info($"Error code: {errorCode}.");
return false;
}
Trace.Info($"Successfully send {signal} to process {_proc.Id}.");
Trace.Info($"Waiting for process exit or {timeout.TotalSeconds} seconds after {signal} signal fired.");
var completedTask = await Task.WhenAny(Task.Delay(timeout), _processExitedCompletionSource.Task);
if (completedTask == _processExitedCompletionSource.Task)
{
Trace.Info("Process exit successfully.");
return true;
}
else
{
Trace.Info($"Process did not honor {signal} signal within {timeout.TotalSeconds} seconds.");
return false;
}
}
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 : RunnerL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
//process 2 new job messages, and one cancel message
public async void TestRunAsync()
{
using (var hc = new TestHostContext(this))
{
//Arrange
var runner = new Runner.Listener.Runner();
hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
hc.SetSingleton<IJobNotification>(_jobNotification.Object);
hc.SetSingleton<IMessageListener>(_messageListener.Object);
hc.SetSingleton<IPromptManager>(_promptManager.Object);
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configStore.Object);
runner.Initialize(hc);
var settings = new RunnerSettings
{
PoolId = 43242
};
var message = new TaskAgentMessage()
{
Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
MessageId = 4234,
MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
};
var messages = new Queue<TaskAgentMessage>();
messages.Enqueue(message);
var signalWorkerComplete = new SemapreplacedSlim(0, 1);
_configurationManager.Setup(x => x.LoadSettings())
.Returns(settings);
_configurationManager.Setup(x => x.IsConfigured())
.Returns(true);
_messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<bool>(true));
_messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()))
.Returns(async () =>
{
if (0 == messages.Count)
{
signalWorkerComplete.Release();
await Task.Delay(2000, hc.RunnerShutdownToken);
}
return messages.Dequeue();
});
_messageListener.Setup(x => x.DeleteSessionAsync())
.Returns(Task.CompletedTask);
_messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()))
.Returns(Task.CompletedTask);
_jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()))
.Callback(() =>
{
});
_jobNotification.Setup(x => x.StartClient(It.IsAny<String>()))
.Callback(() =>
{
});
hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object);
_configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
//Act
var command = new CommandSettings(hc, new string[] { "run" });
Task runnerTask = runner.ExecuteCommand(command);
//replacedert
//wait for the runner to run one job
if (!await signalWorkerComplete.WaitAsync(2000))
{
replacedert.True(false, $"{nameof(_messageListener.Object.GetNextMessageAsync)} was not invoked.");
}
else
{
//Act
hc.ShutdownRunner(ShutdownReason.UserCancelled); //stop Runner
//replacedert
Task[] taskToWait2 = { runnerTask, Task.Delay(2000) };
//wait for the runner to exit
await Task.WhenAny(taskToWait2);
replacedert.True(runnerTask.IsCompleted, $"{nameof(runner.ExecuteCommand)} timed out.");
replacedert.True(!runnerTask.IsFaulted, runnerTask.Exception?.ToString());
replacedert.True(runnerTask.IsCanceled);
_jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()), Times.Once(),
$"{nameof(_jobDispatcher.Object.Run)} was not invoked.");
_messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce());
_messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
_messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
_messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.AtLeastOnce());
// verify that we didn't try to delete local settings file (since we're not ephemeral)
_configurationManager.Verify(x => x.DeleteLocalRunnerConfig(), Times.Never());
}
}
}
19
Source : RunnerL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void TestRunOnceOnlyTakeOneJobMessage()
{
using (var hc = new TestHostContext(this))
{
//Arrange
var runner = new Runner.Listener.Runner();
hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
hc.SetSingleton<IJobNotification>(_jobNotification.Object);
hc.SetSingleton<IMessageListener>(_messageListener.Object);
hc.SetSingleton<IPromptManager>(_promptManager.Object);
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configStore.Object);
runner.Initialize(hc);
var settings = new RunnerSettings
{
PoolId = 43242,
Ephemeral = true
};
var message1 = new TaskAgentMessage()
{
Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
MessageId = 4234,
MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
};
var message2 = new TaskAgentMessage()
{
Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
MessageId = 4235,
MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
};
var messages = new Queue<TaskAgentMessage>();
messages.Enqueue(message1);
messages.Enqueue(message2);
_configurationManager.Setup(x => x.LoadSettings())
.Returns(settings);
_configurationManager.Setup(x => x.IsConfigured())
.Returns(true);
_messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<bool>(true));
_messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()))
.Returns(async () =>
{
if (0 == messages.Count)
{
await Task.Delay(2000);
}
return messages.Dequeue();
});
_messageListener.Setup(x => x.DeleteSessionAsync())
.Returns(Task.CompletedTask);
_messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()))
.Returns(Task.CompletedTask);
var runOnceJobCompleted = new TaskCompletionSource<bool>();
_jobDispatcher.Setup(x => x.RunOnceJobCompleted)
.Returns(runOnceJobCompleted);
_jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()))
.Callback(() =>
{
runOnceJobCompleted.TrySetResult(true);
});
_jobNotification.Setup(x => x.StartClient(It.IsAny<String>()))
.Callback(() =>
{
});
hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object);
_configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
//Act
var command = new CommandSettings(hc, new string[] { "run" });
Task<int> runnerTask = runner.ExecuteCommand(command);
//replacedert
//wait for the runner to run one job and exit
await Task.WhenAny(runnerTask, Task.Delay(30000));
replacedert.True(runnerTask.IsCompleted, $"{nameof(runner.ExecuteCommand)} timed out.");
replacedert.True(!runnerTask.IsFaulted, runnerTask.Exception?.ToString());
replacedert.True(runnerTask.Result == Constants.Runner.ReturnCode.Success);
_jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), true), Times.Once(),
$"{nameof(_jobDispatcher.Object.Run)} was not invoked.");
_messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce());
_messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
_messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
_messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.Once());
}
}
19
Source : RunnerL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void TestRunOnceHandleUpdateMessage()
{
using (var hc = new TestHostContext(this))
{
//Arrange
var runner = new Runner.Listener.Runner();
hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
hc.SetSingleton<IJobNotification>(_jobNotification.Object);
hc.SetSingleton<IMessageListener>(_messageListener.Object);
hc.SetSingleton<IPromptManager>(_promptManager.Object);
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configStore.Object);
hc.SetSingleton<ISelfUpdater>(_updater.Object);
runner.Initialize(hc);
var settings = new RunnerSettings
{
PoolId = 43242,
AgentId = 5678,
Ephemeral = true
};
var message1 = new TaskAgentMessage()
{
Body = JsonUtility.ToString(new AgentRefreshMessage(settings.AgentId, "2.123.0")),
MessageId = 4234,
MessageType = AgentRefreshMessage.MessageType
};
var messages = new Queue<TaskAgentMessage>();
messages.Enqueue(message1);
_updater.Setup(x => x.SelfUpdate(It.IsAny<AgentRefreshMessage>(), It.IsAny<IJobDispatcher>(), It.IsAny<bool>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(true));
_configurationManager.Setup(x => x.LoadSettings())
.Returns(settings);
_configurationManager.Setup(x => x.IsConfigured())
.Returns(true);
_messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<bool>(true));
_messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()))
.Returns(async () =>
{
if (0 == messages.Count)
{
await Task.Delay(2000);
}
return messages.Dequeue();
});
_messageListener.Setup(x => x.DeleteSessionAsync())
.Returns(Task.CompletedTask);
_messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()))
.Returns(Task.CompletedTask);
_jobNotification.Setup(x => x.StartClient(It.IsAny<String>()))
.Callback(() =>
{
});
hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object);
_configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
//Act
var command = new CommandSettings(hc, new string[] { "run" });
Task<int> runnerTask = runner.ExecuteCommand(command);
//replacedert
//wait for the runner to exit with right return code
await Task.WhenAny(runnerTask, Task.Delay(30000));
replacedert.True(runnerTask.IsCompleted, $"{nameof(runner.ExecuteCommand)} timed out.");
replacedert.True(!runnerTask.IsFaulted, runnerTask.Exception?.ToString());
replacedert.True(runnerTask.Result == Constants.Runner.ReturnCode.RunOnceRunnerUpdating);
_updater.Verify(x => x.SelfUpdate(It.IsAny<AgentRefreshMessage>(), It.IsAny<IJobDispatcher>(), false, It.IsAny<CancellationToken>()), Times.Once);
_jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), true), Times.Never());
_messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce());
_messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
_messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
_messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.Once());
}
}
19
Source : RunnerL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void TestRunOnce()
{
using (var hc = new TestHostContext(this))
{
//Arrange
var runner = new Runner.Listener.Runner();
hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
hc.SetSingleton<IJobNotification>(_jobNotification.Object);
hc.SetSingleton<IMessageListener>(_messageListener.Object);
hc.SetSingleton<IPromptManager>(_promptManager.Object);
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configStore.Object);
runner.Initialize(hc);
var settings = new RunnerSettings
{
PoolId = 43242,
Ephemeral = true
};
var message = new TaskAgentMessage()
{
Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
MessageId = 4234,
MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
};
var messages = new Queue<TaskAgentMessage>();
messages.Enqueue(message);
_configurationManager.Setup(x => x.LoadSettings())
.Returns(settings);
_configurationManager.Setup(x => x.IsConfigured())
.Returns(true);
_messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<bool>(true));
_messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()))
.Returns(async () =>
{
if (0 == messages.Count)
{
await Task.Delay(2000);
}
return messages.Dequeue();
});
_messageListener.Setup(x => x.DeleteSessionAsync())
.Returns(Task.CompletedTask);
_messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()))
.Returns(Task.CompletedTask);
var runOnceJobCompleted = new TaskCompletionSource<bool>();
_jobDispatcher.Setup(x => x.RunOnceJobCompleted)
.Returns(runOnceJobCompleted);
_jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()))
.Callback(() =>
{
runOnceJobCompleted.TrySetResult(true);
});
_jobNotification.Setup(x => x.StartClient(It.IsAny<String>()))
.Callback(() =>
{
});
hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object);
_configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
//Act
var command = new CommandSettings(hc, new string[] { "run" });
Task<int> runnerTask = runner.ExecuteCommand(command);
//replacedert
//wait for the runner to run one job and exit
await Task.WhenAny(runnerTask, Task.Delay(30000));
replacedert.True(runnerTask.IsCompleted, $"{nameof(runner.ExecuteCommand)} timed out.");
replacedert.True(!runnerTask.IsFaulted, runnerTask.Exception?.ToString());
replacedert.True(runnerTask.Result == Constants.Runner.ReturnCode.Success);
_jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), true), Times.Once(),
$"{nameof(_jobDispatcher.Object.Run)} was not invoked.");
_messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce());
_messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
_messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
_messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.AtLeastOnce());
// verify that we did try to delete local settings file (since we're ephemeral)
_configurationManager.Verify(x => x.DeleteLocalRunnerConfig(), Times.Once());
}
}
19
Source : DotNetFrameworkTests.cs
with MIT License
from adamant
with MIT License
from adamant
[Fact]
public async Task TaskSelfReferenceDeadlocks()
{
var task = Task.FromResult(1);
task = GetValueAsync(() => task);
var delayTask = Task.Delay((int)TimeSpan.FromSeconds(2).TotalMilliseconds);
var completedTask = await Task.WhenAny(task, delayTask).ConfigureAwait(false);
replacedert.Equal(delayTask, completedTask);
}
19
Source : DotNetFrameworkTests.cs
with MIT License
from adamant
with MIT License
from adamant
[Fact]
public async Task TaskCycleDeadlocks()
{
var t2 = Task.FromResult(2);
var t1 = GetValueAsync(() => t2);
t2 = GetValueAsync(() => t1);
var delayTask = Task.Delay((int)TimeSpan.FromSeconds(2).TotalMilliseconds);
var completedTask = await Task.WhenAny(t1, delayTask).ConfigureAwait(false);
replacedert.Equal(delayTask, completedTask);
}
19
Source : FileLoggerProcessor.cs
with MIT License
from adams85
with MIT License
from adams85
private async Task ResetCoreAsync(Action onQueuesCompleted, bool complete)
{
CancellationTokenSource forcedCompleteTokenSource;
Task[] completionTasks;
lock (_logFiles)
{
if (_status != Status.Running)
return;
forcedCompleteTokenSource = _forcedCompleteTokenSource;
_forcedCompleteTokenSource = new CancellationTokenSource();
completionTasks = _logFiles.Values.Select(async logFile =>
{
logFile.Queue.Writer.Complete();
await logFile.WriteFileTask.ConfigureAwait(false);
if (logFile.IsOpen)
logFile.Close();
}).ToArray();
_logFiles.Clear();
onQueuesCompleted?.Invoke();
if (complete)
_status = Status.Completing;
}
try
{
var completionTimeoutTask = Task.Delay(Context.CompletionTimeout);
if ((await Task.WhenAny(Task.WhenAll(completionTasks), completionTimeoutTask).ConfigureAwait(false)) == completionTimeoutTask)
Context.ReportDiagnosticEvent(new FileLoggerDiagnosticEvent.QueuesCompletionForced(this));
forcedCompleteTokenSource.Cancel();
forcedCompleteTokenSource.Dispose();
}
finally
{
if (complete)
Dispose();
}
}
19
Source : EdgeCasesTest.cs
with MIT License
from adams85
with MIT License
from adams85
[Fact]
public async Task FailingEntryDontGetStuck()
{
var logsDirName = Guid.NewGuid().ToString("D");
var tempPath = Path.Combine(Path.GetTempPath());
var logPath = Path.Combine(tempPath, logsDirName);
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
var fileProvider = new PhysicalFileProvider(tempPath);
var options = new FileLoggerOptions
{
FileAppender = new PhysicalFileAppender(fileProvider),
BasePath = logsDirName,
Files = new[]
{
new LogFileOptions
{
Path = "default.log",
},
},
};
var optionsMonitor = new DelegatedOptionsMonitor<FileLoggerOptions>(_ => options);
var completeCts = new CancellationTokenSource();
var completionTimeoutMs = 2000;
var context = new TestFileLoggerContext(completeCts.Token, TimeSpan.FromMilliseconds(completionTimeoutMs), writeRetryDelay: TimeSpan.FromMilliseconds(250));
context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));
var services = new ServiceCollection();
services.AddOptions();
services.AddLogging(b => b.AddFile(context));
services.AddSingleton<IOptionsMonitor<FileLoggerOptions>>(optionsMonitor);
string filePath = Path.Combine(logPath, "default.log");
try
{
FileLoggerProvider[] providers;
using (ServiceProvider sp = services.BuildServiceProvider())
{
providers = context.GetProviders(sp).ToArray();
replacedert.Equal(1, providers.Length);
var resetTasks = new List<Task>();
foreach (FileLoggerProvider provider in providers)
provider.Reset += (s, e) => resetTasks.Add(e);
ILoggerFactory loggerFactory = sp.GetRequiredService<ILoggerFactory>();
ILogger logger = loggerFactory.CreateLogger("X");
logger.LogInformation("This should get through.");
optionsMonitor.Reload();
// ensuring that reset has been finished and the new settings are effective
await Task.WhenAll(resetTasks);
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
logger.LogInformation("This shouldn't get through.");
Task completion = context.GetCompletion(sp);
replacedert.False(completion.IsCompleted);
completeCts.Cancel();
replacedert.Equal(completion, await Task.WhenAny(completion, Task.Delay(TimeSpan.FromMilliseconds(completionTimeoutMs * 2))));
replacedert.Equal(TaskStatus.RanToCompletion, completion.Status);
}
}
IFileInfo logFile = fileProvider.GetFileInfo($"{logsDirName}/default.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
replacedert.Equal(Encoding.UTF8, encoding);
replacedert.Equal(new[]
{
$"info: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This should get through.",
""
}, lines);
}
finally
{
Directory.Delete(logPath, recursive: true);
}
}
19
Source : AppManager.cs
with MIT License
from admaiorastudio
with MIT License
from admaiorastudio
private async Task ConnectAsync()
{
if (_isConnected)
return;
// Emulators loopback addresses
IPAddress[] loopbackAddresses = new[]
{
IPAddress.Parse("127.0.0.1"),
IPAddress.Parse("10.0.2.2"),
IPAddress.Parse("10.0.3.2"),
IPAddress.Parse("169.254.80.80")
};
// Check if we are an emulator instance
List<Task<string>> waitTasks = new List<Task<string>>();
CancellationTokenSource cts = new CancellationTokenSource();
// Look for server using localhost (an emulator device)
foreach (var ipAddress in loopbackAddresses.Take(1))
{
waitTasks.Add(Task.Run<string>(
async () =>
{
try
{
bool isPortOpen = TryPing(ipAddress.ToString(), 5001, 300);
if (!isPortOpen)
return null;
var connection = new HubConnectionBuilder()
.WithUrl($"http://{ipAddress.ToString()}:5001/hub")
.Build();
await connection.StartAsync(cts.Token);
if (cts.IsCancellationRequested)
return null;
_useLocalHost = true;
_hubConnection = connection;
cts.Cancel();
return ipAddress.ToString();
}
catch (Exception ex)
{
return null;
}
}, cts.Token));
}
// Look for server using broadcast (a real device)
waitTasks.Add(Task.Run<string>(
async () =>
{
// Discover the server
using (UdpClient client = new UdpClient())
{
client.EnableBroadcast = true;
byte[] requestData = Encoding.ASCII.GetBytes($"AreYouTheServer?");
Task<int> sendTask = client.SendAsync(requestData, requestData.Length, new IPEndPoint(IPAddress.Broadcast, 5002));
await Task.WhenAny(new[] { sendTask, Task.Delay(300) });
if (sendTask.IsCompleted)
{
if (cts.IsCancellationRequested)
return null;
Task<UdpReceiveResult> receiveTask = client.ReceiveAsync();
await Task.WhenAny(new[] { receiveTask, Task.Delay(300) });
if (receiveTask.IsCompleted)
{
if (cts.IsCancellationRequested)
return null;
UdpReceiveResult serverResponseData = receiveTask.Result;
string serverResponse = Encoding.ASCII.GetString(serverResponseData.Buffer);
if (serverResponse == "YesIamTheServer!")
{
string ipAddress = serverResponseData.RemoteEndPoint.Address.ToString();
_useLocalHost = false;
_hubConnection = null;
cts.Cancel();
return ipAddress.ToString();
}
}
}
client.Close();
}
return null;
}));
// Timeout task
waitTasks.Add(Task.Run<string>(
async () =>
{
try
{
await Task.Delay(5000, cts.Token);
cts.Cancel();
return null;
}
catch
{
return null;
}
}));
try
{
string ipAddress = await WaitForAnyGetHostIpTaskAsync(waitTasks);
if (ipAddress != null)
{
if (_hubConnection == null)
{
string port = _useLocalHost ? "5001" : "5002";
_hubConnection = new HubConnectionBuilder()
.WithUrl($"http://{ipAddress.ToString()}:{port}/hub")
.Build();
await _hubConnection.StartAsync();
}
_isConnected = true;
_serverAddress = ipAddress;
_hubConnection.Closed +=
async (error) =>
{
System.Diagnostics.Debug.WriteLine("Connection with RealXaml has been lost.");
while(_hubConnection.State == HubConnectionState.Disconnected)
{
bool isPortOpen = TryPing(ipAddress.ToString(), 5001, 300);
if (isPortOpen)
{
System.Diagnostics.Debug.WriteLine("Trying to reconnect again...");
await _hubConnection.StartAsync();
if (_hubConnection.State == HubConnectionState.Connected)
{
await Task.Delay(300);
await _hubConnection.SendAsync("NotifyIde", "Connection was lost. Here I'am again.");
System.Diagnostics.Debug.WriteLine($"Successfully restored lost to the RealXaml server.");
break;
}
}
System.Diagnostics.Debug.WriteLine("Unable to connect. Retrying in 5secs.");
await Task.Delay(5000);
}
};
_hubConnection.On<string, byte[], bool>("ReloadXaml",
async (pageId, data, refresh) => await WhenReloadXaml(pageId, data, refresh));
_hubConnection.On<string, byte[]>("Reloadreplacedembly",
async (replacedemblyName, data) => await WhenReloadreplacedembly(replacedemblyName, data));
string clientId = $"RXID-{DateTime.Now.Ticks}";
await _hubConnection.SendAsync("RegisterClient", clientId);
System.Diagnostics.Debug.WriteLine($"Successfully connected to the RealXaml server.");
System.Diagnostics.Debug.WriteLine($"Your client ID is {clientId}");
return;
}
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error while trying to connect to the RealXaml server.");
System.Diagnostics.Debug.WriteLine(ex);
}
}
19
Source : RetryableWebSocketConnection.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
private async Task PullAndMonitorInThisThread(Func<List<Commit<T>>, Task> onData, Func<string> startPositionFactory, Func<Task> onConnected)
{
var exitTask = Task.Run(() => _exitEvent.WaitOne());
var retryGapSeconds = 1;
var connectedTime = DateTime.MinValue;
while (!exitTask.IsCompleted)
{
try
{
connectedTime = DateTime.UtcNow;
AttemptCount++;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(AttemptCount)));
await base.PullAndMonitor(onData, startPositionFactory, onConnected: () =>
{
IsConnectionHealthy = true;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsConnectionHealthy)));
return onConnected();
}, true);
}
catch (WebSocketException)
{
IsConnectionHealthy = false;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsConnectionHealthy)));
OnReconnecting?.Invoke();
if (DateTime.UtcNow - connectedTime > TimeSpan.FromMinutes(1))
{
// Connection held for one minute. Seems to be a healthy server. Retry soon.
retryGapSeconds = 1;
}
// When retry time finish, or asked to finished.
await Task.WhenAny(Task.Delay(TimeSpan.FromSeconds(retryGapSeconds)), exitTask);
if (retryGapSeconds < 128)
{
retryGapSeconds *= 2;
}
}
}
}
19
Source : Coroutine.cs
with GNU Affero General Public License v3.0
from akira0245
with GNU Affero General Public License v3.0
from akira0245
public static async Task WaitWhile(Func<bool> condition, int timeout = -1, int frequency = 25)
{
var waitTask = Task.Run(async () =>
{
while (condition())
{
await Task.Delay(frequency);
}
});
if (waitTask != await Task.WhenAny(waitTask, Task.Delay(timeout)))
{
throw new TimeoutException();
}
}
19
Source : Coroutine.cs
with GNU Affero General Public License v3.0
from akira0245
with GNU Affero General Public License v3.0
from akira0245
public static async Task WaitUntil(Func<bool> condition, int timeout = -1, int frequency = 25)
{
var waitTask = Task.Run(async () =>
{
while (!condition())
{
await Task.Delay(frequency);
}
});
if (waitTask != await Task.WhenAny(
waitTask,
Task.Delay(timeout)))
{
throw new TimeoutException();
}
}
19
Source : BugFix240SupervisionStrategy.cs
with Apache License 2.0
from akkadotnet
with Apache License 2.0
from akkadotnet
private static async Task GuardWithTimeoutAsync(Task asyncTask, TimeSpan timeout)
{
var cts = new CancellationTokenSource();
try
{
var timeoutTask = Task.Delay(timeout, cts.Token);
var completedTask = await Task.WhenAny(asyncTask, timeoutTask);
if (completedTask == timeoutTask)
throw new TimeoutException($"Task exceeds timeout duration {timeout}");
else
cts.Cancel();
}
finally
{
cts.Dispose();
}
}
19
Source : ConsumerSpec.cs
with Apache License 2.0
from akkadotnet
with Apache License 2.0
from akkadotnet
public static async Task WithTimeout(this Task task, TimeSpan timeout)
{
using (var cts = new CancellationTokenSource())
{
var timeoutTask = Task.Delay(timeout, cts.Token);
var completed = await Task.WhenAny(task, timeoutTask);
if (completed == timeoutTask)
throw new OperationCanceledException("Operation timed out");
else
cts.Cancel();
}
}
19
Source : TcpClientExtensions.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
public static async Task<bool> TryConnectAsync(this TcpClient tcpClient, IPAddress address, int port, int timeout, CancellationToken token)
{
var connectTask = tcpClient.ConnectAsync(address, port);
var timeoutTask = Task.Delay(timeout, token);
await Task.WhenAny(connectTask, timeoutTask);
if (connectTask.IsCompleted)
return true;
tcpClient.Close();
return false;
}
19
Source : UdpClientExtensions.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
public static async Task<UdpReceiveResult> ReceiveAsync(this UdpClient udpClient, int timeout, CancellationToken token)
{
var connectTask = udpClient.ReceiveAsync();
var timeoutTask = Task.Delay(timeout, token);
await Task.WhenAny(connectTask, timeoutTask);
if (connectTask.IsCompleted)
return connectTask.Result;
return new UdpReceiveResult();
}
19
Source : BusExtensions.cs
with GNU General Public License v3.0
from Amazing-Favorites
with GNU General Public License v3.0
from Amazing-Favorites
public static async Task<TResponse> SendRequest<TRequest, TResponse>(this IBus dispatcher,
TRequest request)
where TRequest : IRequest
where TResponse : IResponse
{
var requestTypeName = typeof(TRequest).Name;
var responseTypeName = typeof(TResponse).Name;
var channelMessage = new BusMessage
{
MessageId = RandomIdHelper.GetId(),
MessageType = requestTypeName,
PayloadJson = JsonSerializer.Serialize((object)request)
};
var tcs = new TaskCompletionSource<TResponse>();
dispatcher.RegisterHandler(responseTypeName, (scope, responseMessage) =>
{
if (responseMessage.ParentMessageId == channelMessage.MessageId)
{
var payloadJson = responseMessage.PayloadJson;
if (string.IsNullOrEmpty(payloadJson))
{
return false;
}
var result = (TResponse)JsonSerializer.Deserialize(payloadJson, typeof(TResponse))!;
tcs.TrySetResult(result);
return true;
}
return false;
}, channelMessage.MessageId);
await dispatcher.SendMessage(channelMessage);
var delay = Task.Delay(TimeSpan.FromSeconds(Bus.DefaultExpiredDuration));
var resultTask = await Task.WhenAny(delay, tcs.Task);
if (resultTask == delay)
{
tcs.TrySetException(new TimeoutException());
}
return tcs.Task.Result;
}
19
Source : Utils.cs
with MIT License
from AmazingDM
with MIT License
from AmazingDM
public static async Task<int> TCPingAsync(IPAddress ip, int port, int timeout = 1000, CancellationToken ct = default)
{
using var client = new TcpClient(ip.AddressFamily);
var stopwatch = Stopwatch.StartNew();
var task = client.ConnectAsync(ip, port);
var resTask = await Task.WhenAny(task, Task.Delay(timeout, ct));
stopwatch.Stop();
if (resTask == task && client.Connected)
{
var t = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds);
return t;
}
return timeout;
}
19
Source : TaskExtensions.cs
with Apache License 2.0
from Anapher
with Apache License 2.0
from Anapher
public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout)
{
using (var timeoutCancellationTokenSource = new CancellationTokenSource())
{
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
if (completedTask == task)
{
timeoutCancellationTokenSource.Cancel();
return await task; // Very important in order to propagate exceptions
}
throw new TimeoutException("The operation has timed out.");
}
}
19
Source : TaskExtensions.cs
with Apache License 2.0
from Anapher
with Apache License 2.0
from Anapher
public static async Task TimeoutAfter(this Task task, TimeSpan timeout)
{
using (var timeoutCancellationTokenSource = new CancellationTokenSource())
{
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
if (completedTask == task)
{
timeoutCancellationTokenSource.Cancel();
await task; // Very important in order to propagate exceptions
return;
}
throw new TimeoutException("The operation has timed out.");
}
}
19
Source : ModbusClient.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public async Task Connect(CancellationToken cancellationToken = default)
{
var cancelTask = ReconnectTimeSpan == TimeSpan.MaxValue
? Task.Delay(Timeout.Infinite, cancellationToken)
: Task.Delay(ReconnectTimeSpan, cancellationToken);
try
{
logger?.LogTrace("ModbusClient.Connect enter");
CheckDisposed();
if (isStarted)
{
await Task.WhenAny(ConnectingTask, cancelTask);
return;
}
isStarted = true;
stopCts = new CancellationTokenSource();
logger?.LogInformation("ModbusClient starting.");
if (DriverEnableRS485 && RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
try
{
var rs485 = GetDriverState();
serialDriverFlags = rs485.Flags;
rs485.Flags |= RS485Flags.Enabled;
rs485.Flags &= ~RS485Flags.RxDuringTx;
SetDriverState(rs485);
driverModified = true;
}
catch (Exception ex)
{
logger?.LogError(ex, $"Set driver state to RS485 failed: {ex.GetMessage()}");
throw;
}
}
lock (reconnectLock)
{
IsConnected = false;
wasConnected = false;
ConnectingTask = GetReconnectTask(true);
}
logger?.LogInformation("Modbus client started.");
await Task.WhenAny(ConnectingTask, cancelTask);
}
finally
{
if (cancelTask.Status != TaskStatus.WaitingForActivation)
cancelTask.Dispose();
logger?.LogTrace("ModbusClient.Connect 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 : ModbusClient.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public async Task Connect(CancellationToken cancellationToken = default)
{
var cancelTask = ReconnectTimeSpan == TimeSpan.MaxValue
? Task.Delay(Timeout.Infinite, cancellationToken)
: Task.Delay(ReconnectTimeSpan, cancellationToken);
try
{
logger?.LogTrace("ModbusClient.Connect enter");
CheckDisposed();
if (isStarted)
{
await Task.WhenAny(ConnectingTask, cancelTask);
return;
}
isStarted = true;
stopCts = new CancellationTokenSource();
logger?.LogInformation("Modbus client starting.");
lock (reconnectLock)
{
transactionId = 0;
IsConnected = false;
wasConnected = false;
ConnectingTask = GetReconnectTask(true);
}
logger?.LogInformation("Modbus client started.");
await Task.WhenAny(ConnectingTask, cancelTask);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{ }
finally
{
if (cancelTask.Status != TaskStatus.WaitingForActivation)
cancelTask.Dispose();
logger?.LogTrace("ModbusClient.Connect leave");
}
}
19
Source : ModbusClient.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public async Task Disconnect(CancellationToken cancellationToken = default)
{
try
{
logger?.LogTrace("ModbusClient.Disconnect enter");
CheckDisposed();
if (!isStarted)
return;
logger?.LogInformation("Modbus client stopping.");
stopCts.Cancel();
receiveCts?.Cancel();
bool connected = false;
lock (reconnectLock)
{
connected = IsConnected;
IsConnected = false;
wasConnected = false;
}
await Task.WhenAny(ConnectingTask, Task.Delay(Timeout.Infinite, cancellationToken));
stream?.Dispose();
tcpClient?.Dispose();
isStarted = false;
logger?.LogInformation("Modbus client stopped.");
if (connected)
Task.Run(() => Disconnected?.Invoke(this, EventArgs.Empty)).Forget();
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{ }
finally
{
logger?.LogTrace("ModbusClient.Disconnect 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 ? "Rec" : "C")}onnect starting.");
if (wasConnected)
{
receiveCts?.Cancel();
await receiveTask;
receiveCts = null;
receiveTask = Task.CompletedTask;
Task.Run(() => Disconnected?.Invoke(this, EventArgs.Empty)).Forget();
}
var timeout = TimeSpan.FromSeconds(2);
var startTime = DateTime.UtcNow;
var address = ResolveHost(Host);
while (!stopCts.IsCancellationRequested)
{
try
{
stream?.Dispose();
stream = null;
tcpClient?.Dispose();
tcpClient = new TcpClient(address.AddressFamily);
var connectTask = tcpClient.ConnectAsync(address, Port);
if (await Task.WhenAny(connectTask, Task.Delay(timeout, stopCts.Token)) == connectTask && tcpClient.Connected)
{
SetKeepAlive();
stream = tcpClient.GetStream();
receiveCts = new CancellationTokenSource();
receiveTask = Task.Run(async () => await ReceiveLoop());
lock (reconnectLock)
{
IsConnected = true;
wasConnected = true;
reconnectTcs?.TrySetResult(true);
Task.Run(() => Connected?.Invoke(this, EventArgs.Empty)).Forget();
}
logger?.LogInformation($"{(wasConnected ? "Rec" : "C")}onnected successfully.");
return;
}
else
{
if (timeout < MaxConnectTimeout)
{
logger?.LogWarning($"{(wasConnected ? "Rec" : "C")}onnect failed within {timeout}.");
timeout = timeout.Add(TimeSpan.FromSeconds(2));
if (timeout > MaxConnectTimeout)
timeout = MaxConnectTimeout;
}
throw new SocketException((int)SocketError.TimedOut);
}
}
catch (SocketException) when (ReconnectTimeSpan == TimeSpan.MaxValue || DateTime.UtcNow - startTime <= ReconnectTimeSpan)
{
await Task.Delay(1000, stopCts.Token);
continue;
}
catch (OperationCanceledException) when (stopCts.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
logger?.LogError(ex, $"{(wasConnected ? "Rec" : "C")}onnecting failed: {ex.GetMessage()}, trying again.");
}
}
}
catch (OperationCanceledException) when (stopCts.IsCancellationRequested)
{
reconnectTcs?.TrySetCanceled();
}
catch (Exception ex)
{
logger?.LogError(ex, $"{(wasConnected ? "Rec" : "C")}onnecting failed: {ex.GetMessage()}");
reconnectTcs?.TrySetException(ex);
}
finally
{
lock (reconnectLock)
{
isReconnecting = false;
reconnectTcs = null;
}
logger?.LogTrace("ModbusClient.Reconnect leave");
}
}
19
Source : AsyncAutoResetEvent.cs
with MIT License
from andyalm
with MIT License
from andyalm
public async Task<bool> WaitAsync(TimeSpan timeout, CancellationToken cancellationToken)
{
TaskCompletionSource<bool> tcs;
lock (this.waiters)
{
if (this.isSignaled)
{
this.isSignaled = false;
return true;
}
else if (timeout == TimeSpan.Zero)
{
return this.isSignaled;
}
else
{
tcs = new TaskCompletionSource<bool>();
this.waiters.AddLast(tcs);
}
}
Task winner = await Task.WhenAny(tcs.Task, Task.Delay(timeout, cancellationToken));
if (winner == tcs.Task)
{
// The task was signaled.
return true;
}
else
{
// We timed-out; remove our reference to the task.
// This is an O(n) operation since waiters is a LinkedList<T>.
lock (this.waiters)
{
bool removed = this.waiters.Remove(tcs);
Debug.replacedert(removed);
return false;
}
}
}
19
Source : UniFiApi.Discovery.cs
with MIT License
from anthturner
with MIT License
from anthturner
private async static Task<DeviceInformation> DiscoverController(IPAddress ip, int port, byte[] message, SocketFlags flags)
{
try
{
var endpoint = new IPEndPoint(ip, port);
var udp = new UdpClient();
var result = await udp.SendAsync(message, message.Length, endpoint);
var receiveTask = udp.ReceiveAsync();
await Task.WhenAny(receiveTask, Task.Delay(UDP_TIMEOUT_MS));
if (receiveTask.IsCompleted)
return await DeviceInformation.Parse(receiveTask.Result.RemoteEndPoint, receiveTask.Result.Buffer);
return null;
}
catch { return null; }
}
19
Source : Producer.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private async Task Monitor()
{
var numberOfParreplacedions = await GetNumberOfParreplacedions(Topic, _cts.Token).ConfigureAwait(false);
var isParreplacedionedTopic = numberOfParreplacedions != 0;
var monitoringTasks = new Task<ProducerStateChanged>[isParreplacedionedTopic ? numberOfParreplacedions : 1];
var topic = Topic;
for (var parreplacedion = 0; parreplacedion < monitoringTasks.Length; ++parreplacedion)
{
if (isParreplacedionedTopic)
topic = $"{Topic}-parreplacedion-{parreplacedion}";
var producer = CreateSubProducer(topic);
_ = _producers.TryAdd(parreplacedion, producer);
monitoringTasks[parreplacedion] = producer.StateChangedFrom(ProducerState.Disconnected, _cts.Token).AsTask();
}
Interlocked.Exchange(ref _producerCount, monitoringTasks.Length);
var connectedProducers = 0;
while (true)
{
await Task.WhenAny(monitoringTasks).ConfigureAwait(false);
for (var i = 0; i < monitoringTasks.Length; ++i)
{
var task = monitoringTasks[i];
if (!task.IsCompleted)
continue;
var state = task.Result.ProducerState;
switch (state)
{
case ProducerState.Connected:
++connectedProducers;
break;
case ProducerState.Disconnected:
--connectedProducers;
break;
case ProducerState.Faulted:
_state.SetState(ProducerState.Faulted);
return;
}
monitoringTasks[i] = task.Result.Producer.StateChangedFrom(state, _cts.Token).AsTask();
}
if (connectedProducers == 0)
_state.SetState(ProducerState.Disconnected);
else if (connectedProducers == monitoringTasks.Length)
_state.SetState(ProducerState.Connected);
else
_state.SetState(ProducerState.PartiallyConnected);
}
}
19
Source : IOutboxProducer.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public async Task StopAsync(CancellationToken ctk)
{
_processorCT?.Dispose();
await Task.WhenAny(_processorTask, Task.Delay(Timeout.Infinite, ctk));
}
19
Source : TaskExtensions.cs
with Apache License 2.0
from asynkron
with Apache License 2.0
from asynkron
public static async Task<TResult> WithTimeout<TResult>(this Task<TResult> task, TimeSpan timeout)
{
using var timeoutCancellationTokenSource = new CancellationTokenSource();
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
if (completedTask != task) throw new TimeoutException("The operation has timed out.");
timeoutCancellationTokenSource.Cancel();
return await task; // Very important in order to propagate exceptions
}
19
Source : TaskTimeoutExtensions.cs
with MIT License
from aurelia
with MIT License
from aurelia
public static async Task WithTimeout(this Task task, TimeSpan timeoutDelay, string message)
{
if (task == await Task.WhenAny(task, Task.Delay(timeoutDelay)))
{
task.Wait(); // Allow any errors to propagate
}
else
{
throw new TimeoutException(message);
}
}
19
Source : TaskTimeoutExtensions.cs
with MIT License
from aurelia
with MIT License
from aurelia
public static async Task<T> WithTimeout<T>(this Task<T> task, TimeSpan timeoutDelay, string message)
{
if (task == await Task.WhenAny(task, Task.Delay(timeoutDelay)))
{
return task.Result;
}
else
{
throw new TimeoutException(message);
}
}
19
Source : TimerHostedServiceBase.cs
with MIT License
from Avanade
with MIT License
from Avanade
async Task IHostedService.StopAsync(CancellationToken cancellationToken)
{
Logger.LogInformation($"{ServiceName} service stop requested.");
_timer!.Change(Timeout.Infinite, Timeout.Infinite);
try
{
_cts!.Cancel();
}
finally
{
await Task.WhenAny(_executeTask ?? Task.CompletedTask, Task.Delay(Timeout.Infinite, cancellationToken)).ConfigureAwait(false);
}
await StoppingAsync(cancellationToken).ConfigureAwait(false);
Logger.LogInformation($"{ServiceName} service stopped.");
}
19
Source : LightBackgroundTask.cs
with MIT License
from Avanade
with MIT License
from Avanade
public virtual async Task StopAsync(CancellationToken cancellationToken)
{
if (_executingTask == null)
return;
try
{
_cancelToken.Cancel();
}
finally
{
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken));
}
}
19
Source : PackageInstaller.cs
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
private async Task RunCommand(string command, string arguments)
{
try
{
Process process = new Process();
process.StartInfo.FileName = command;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
//The following code will pipe the output of the Command to KinesisTap for up to 2 second
//Then it will exit because it sometimes interfere with service restart
while (!process.HasExited)
{
const int timeout = 2000;
var outputTask = PipeOutputAsync(process);
if (await Task.WhenAny(outputTask, Task.Delay(timeout)) == outputTask)
{
continue;
}
else
{
break;
}
}
}
catch (Exception ex)
{
_logger?.LogError($"Error starting command {command}: {ex.ToMinimized()}");
}
}
19
Source : TaskExtensions.cs
with MIT License
from Azure
with MIT License
from Azure
public static async Task TimeoutAfter(this Task task, TimeSpan timeout,
[CallerFilePath] string filePath = null,
[CallerLineNumber] int lineNumber = default)
{
// Don't create a timer if the task is already completed
// or the debugger is attached
if (task.IsCompleted || Debugger.IsAttached)
{
await task;
return;
}
var cts = new CancellationTokenSource();
if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)))
{
cts.Cancel();
await task;
}
else
{
throw new TimeoutException(CreateMessage(timeout, filePath, lineNumber));
}
}
19
Source : LogDecoratorBase.cs
with MIT License
from Azure
with MIT License
from Azure
protected async Task<T> MakeDependencyCall<T>(Task<T> dataProviderTask, [CallerMemberName]string dataProviderOperation = "")
{
Exception dataProviderException = null;
DateTime startTime = DateTime.UtcNow, endTime;
CancellationTokenRegistration cTokenRegistration;
try
{
var tcs = new TaskCompletionSource<bool>();
using (cTokenRegistration = _dataSourceCancellationToken.Register(() => tcs.TrySetResult(true)))
{
var completedTask = await Task.WhenAny(new Task[] { dataProviderTask, tcs.Task });
if (completedTask.Id == dataProviderTask.Id)
{
return await dataProviderTask;
}
else
{
var dataSourceName = this.GetType().Name;
var logDecoratorSuffix = "LogDecorator";
if (dataSourceName.EndsWith(logDecoratorSuffix, StringComparison.InvariantCultureIgnoreCase))
{
dataSourceName = dataSourceName.Substring(0, dataSourceName.Length - logDecoratorSuffix.Length);
}
throw new TimeoutException($"DataSource timed out: {dataSourceName}");
}
}
}
catch (Exception ex)
{
dataProviderException = ex;
throw;
}
finally
{
endTime = DateTime.UtcNow;
var latencyMilliseconds = Convert.ToInt64((endTime - startTime).TotalMilliseconds);
if (dataProviderException != null)
{
DiagnosticsETWProvider.Instance.LogDataProviderException(_requestId, dataProviderOperation,
startTime.ToString("HH:mm:ss.fff"), endTime.ToString("HH:mm:ss.fff"),
latencyMilliseconds, dataProviderException.GetType().ToString(), dataProviderException.ToString());
}
else
{
DiagnosticsETWProvider.Instance.LogDataProviderOperationSummary(_requestId, dataProviderOperation, startTime.ToString("HH:mm:ss.fff"),
endTime.ToString("HH:mm:ss.fff"), latencyMilliseconds);
}
}
}
See More Examples