Here are the examples of the csharp api System.Threading.Tasks.TaskCompletionSource.SetResult(bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
840 Examples
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 : VideoSource.cs
with MIT License
from adamfisher
with MIT License
from adamfisher
protected void OnLoadingCompleted(bool cancelled)
{
if (!IsLoading || this._completionSource == null)
return;
var completionSource = Interlocked.Exchange(ref this._completionSource, null);
completionSource?.SetResult(cancelled);
var obj = _syncHandle;
var lockTaken = false;
try
{
Monitor.Enter(obj, ref lockTaken);
CancellationTokenSource = null;
}
finally
{
if (lockTaken)
Monitor.Exit(obj);
}
}
19
Source : CoverageService.cs
with MIT License
from ademanuele
with MIT License
from ademanuele
private async void UnitTestService_TestSessionStarting(object sender, TestSessionEventArgs e)
{
if (coverageCollectionCompletion == null || e.Test.OwnerObject is not Project testProject) return;
var configuration = IdeApp.Workspace.ActiveConfiguration;
XmlNode coverageSettings = GetRunSettings(testProject);
provider.Prepare(new CoverageSettings(testProject, configuration, coverageSettings));
await e.Session.Task;
var results = provider.GetCoverage(testProject, configuration);
if (results != null) SaveResults(results, testProject, configuration);
coverageCollectionCompletion.SetResult(true);
}
19
Source : AppManager.cs
with MIT License
from admaiorastudio
with MIT License
from admaiorastudio
internal void Setup(Application application)
{
if (application == null)
throw new ArgumentNullException("application");
AppDomain.CurrentDomain.UnhandledException += this.CurrentDomain_UnhandledException;
TaskScheduler.UnobservedTaskException += this.TaskScheduler_UnobservedTaskException;
_app = new WeakReference<Application>(application);
application.PageAppearing += Application_PageAppearing;
application.PageDisappearing += Application_PageDisappearing;
_connectionTCS = new TaskCompletionSource<bool>();
Task.Run(
async () =>
{
try
{
await ConnectAsync();
if (_isConnected)
{
// Connection successfully estabilished
_connectionTCS.SetResult(_isConnected);
}
else
{
// Unable to connect, we should retry later
_connectionTCS.SetResult(_isConnected);
System.Diagnostics.Debug.WriteLine("Unable to connect to the RealXaml server.");
while (true)
{
System.Diagnostics.Debug.WriteLine("Trying to reconnect again...");
await ConnectAsync();
if (_isConnected)
{
break;
}
System.Diagnostics.Debug.WriteLine("Unable to connect. Retrying in 5secs.");
await Task.Delay(5000);
}
}
}
catch(Exception ex)
{
_connectionTCS.SetException(ex);
}
});
}
19
Source : AsyncConnector.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public Task<bool> ConnectAsync()
{
this.InitConnection();
if (_redisSocket.Connected)
_connectionTaskSource.SetResult(true);
if (!_asyncConnectionStarted && !_redisSocket.Connected)
{
lock (_asyncConnectArgs)
{
if (!_asyncConnectionStarted && !_redisSocket.Connected)
{
_asyncConnectionStarted = true;
if (!_redisSocket.ConnectAsync(_asyncConnectArgs))
OnSocketConnected(_asyncConnectArgs);
}
}
} else if (_connectionTaskSource.Task.IsCompleted == false)
_connectionTaskSource.SetResult(false);
return _connectionTaskSource.Task;
}
19
Source : AsyncConnector.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
void OnSocketConnected(SocketAsyncEventArgs args)
{
if (Connected != null)
Connected(this, new EventArgs());
_connectionTaskSource.SetResult(_redisSocket.Connected);
}
19
Source : Amb.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
private void First(Task<bool> task, InnerHandler sender)
{
if (sender.CheckDisposed())
{
Dispose(sender.Source);
}
else
{
if (Volatile.Read(ref _winner) == null && Interlocked.CompareExchange(ref _winner, sender, null) == null)
{
if (task.IsCanceled)
{
_winTask.TrySetCanceled();
}
else if (task.IsFaulted)
{
_winTask.TrySetException(ExceptionHelper.Extract(task.Exception));
}
else
{
_winTask.SetResult(task.Result);
}
}
}
}
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 : DownloadUpdateDialog.cs
with MIT License
from Analogy-LogViewer
with MIT License
from Analogy-LogViewer
private void DownloadUpdateDialogLoad(object sender, EventArgs e)
{
_webClient = new MyWebClient
{
CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore)
};
if (Proxy != null)
{
_webClient.Proxy = Proxy;
}
var uri = new Uri(_downloadURL);
if (BasicAuthDownload != null)
{
_webClient.Headers[HttpRequestHeader.Authorization] = BasicAuthDownload.ToString();
}
_webClient.DownloadProgressChanged += OnDownloadProgressChanged;
_webClient.DownloadFileCompleted += WebClientOnDownloadFileCompleted;
_webClient.DownloadFileAsync(uri, _tempFile);
void WebClientOnDownloadFileCompleted(object sender, AsyncCompletedEventArgs asyncCompletedEventArgs)
{
if (asyncCompletedEventArgs.Cancelled)
{
_taskCompletionSource.SetResult(false);
return;
}
UnzipZipFileIntoTempFolder(_tempFile, _targetFolder);
if (asyncCompletedEventArgs.Error != null)
{
XtraMessageBox.Show(asyncCompletedEventArgs.Error.Message,
asyncCompletedEventArgs.Error.GetType().ToString(), MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
_webClient?.Dispose();
DialogResult = DialogResult.OK;
_taskCompletionSource.SetResult(true);
Close();
}
}
19
Source : BaseContextMenuView.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
public virtual async void ForceOpen(bool animated = true)
{
SetContextViewIfNeeded();
var context = ContextView;
if (context == null)
{
return;
}
var width = Math.Max(context.Width, context.WidthRequest);
var widthCompletionSource = new TaskCompletionSource<bool>();
if (width <= 0)
{
EventHandler onSizeChanged = null;
onSizeChanged = (sender, e) =>
{
var v = (View)sender;
if (v.Width > 0 && v.Height > 0)
{
v.SizeChanged -= onSizeChanged;
widthCompletionSource.SetResult(true);
}
};
context.SizeChanged += onSizeChanged;
}
else
{
widthCompletionSource.SetResult(true);
}
await widthCompletionSource.Task;
ForceOpenContextMenu(this, animated);
}
19
Source : BaseActionViewCell.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
public virtual async void ForceOpen(bool animated = true)
{
SetContextViewIfNeeded();
var context = Scroll.ContextView;
if(context == null)
{
return;
}
var width = Math.Max(context.Width, context.WidthRequest);
var widthCompletionSource = new TaskCompletionSource<bool>();
if(width <= 0)
{
EventHandler onSizeChanged = null;
onSizeChanged = (sender, e) =>
{
var v = (View)sender;
if (v.Width > 0 && v.Height > 0)
{
v.SizeChanged -= onSizeChanged;
widthCompletionSource.SetResult(true);
}
};
context.SizeChanged += onSizeChanged;
}
else
{
widthCompletionSource.SetResult(true);
}
await widthCompletionSource.Task;
Scroll.ForceOpenContextMenu(Scroll, animated);
}
19
Source : ContextMenuScrollView.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
public virtual async Task OnFlingStarted(bool needScroll = true, bool animated = true, bool inMainThread = false)
{
HasBeenAccelerated = true;
if (needScroll)
{
var task = ScrollToAsync(IsOpenDirection ? ContextView.Width : 0, 0, animated);
if (inMainThread)
{
var completionSource = new TaskCompletionSource<bool>();
Device.BeginInvokeOnMainThread(async () =>
{
await task;
completionSource.SetResult(true);
});
await completionSource.Task;
return;
}
await task;
}
}
19
Source : AnimationWrapper.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
public Task Commit(View view, string name, uint rate = 16u, uint length = 250u, Easing easing = null)
{
if (DependencyService.Get<IAnimationsChecker>()?.AreAnimationsEnabled ?? true)
{
var tcs = new TaskCompletionSource<bool>();
PrepareAnimation(this).Commit(view, name, rate, length, easing, (d, b) => tcs.SetResult(true));
return tcs.Task;
}
try
{
view.BatchBegin();
CommitWithoutAnimation(this);
}
finally
{
view.BatchCommit();
}
return Task.FromResult(true);
}
19
Source : TouchVisualManager.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
private async Task SetBackgroundColorAsync(TouchEff sender, TouchState touchState, HoverState hoverState, int duration, Easing easing)
{
var regularBackgroundColor = sender.RegularBackgroundColor;
var pressedBackgroundColor = sender.PressedBackgroundColor;
var hoveredBackgroundColor = sender.HoveredBackgroundColor;
if (regularBackgroundColor == Color.Default &&
pressedBackgroundColor == Color.Default &&
hoveredBackgroundColor == Color.Default)
{
return;
}
var control = sender.Control;
if (_defaultBackgroundColor == default(Color))
_defaultBackgroundColor = control.BackgroundColor;
var color = GetBackgroundColor(regularBackgroundColor);
if (touchState == TouchState.Pressed)
{
color = GetBackgroundColor(pressedBackgroundColor);
}
else if (hoverState == HoverState.Hovering)
{
color = GetBackgroundColor(hoveredBackgroundColor);
}
if (duration <= 0)
{
control.BackgroundColor = color;
return;
}
var animationCompletionSource = new TaskCompletionSource<bool>();
new Animation{
{0, 1, new Animation(v => control.BackgroundColor = new Color(v, control.BackgroundColor.G, control.BackgroundColor.B, control.BackgroundColor.A), control.BackgroundColor.R, color.R) },
{0, 1, new Animation(v => control.BackgroundColor = new Color(control.BackgroundColor.R, v, control.BackgroundColor.B, control.BackgroundColor.A), control.BackgroundColor.G, color.G) },
{0, 1, new Animation(v => control.BackgroundColor = new Color(control.BackgroundColor.R, control.BackgroundColor.G, v, control.BackgroundColor.A), control.BackgroundColor.B, color.B) },
{0, 1, new Animation(v => control.BackgroundColor = new Color(control.BackgroundColor.R, control.BackgroundColor.G, control.BackgroundColor.B, v), control.BackgroundColor.A, color.A) },
}.Commit(sender.Control, ChangeBackgroundColorAnimationName, 16, (uint)duration, easing, (d, b) => animationCompletionSource.SetResult(true));
await animationCompletionSource.Task;
}
19
Source : TouchVisualManager.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
private async Task SetScaleAsync(TouchEff sender, TouchState touchState, HoverState hoverState, int duration, Easing easing)
{
var regularScale = sender.RegularScale;
var pressedScale = sender.PressedScale;
var hoveredScale = sender.HoveredScale;
if (Abs(regularScale - 1) <= double.Epsilon &&
Abs(pressedScale - 1) <= double.Epsilon &&
Abs(hoveredScale - 1) <= double.Epsilon)
{
return;
}
var scale = regularScale;
if (touchState == TouchState.Pressed)
{
scale = pressedScale;
}
else if (hoverState == HoverState.Hovering)
{
scale = hoveredScale;
}
var control = sender.Control;
var tcs = new TaskCompletionSource<bool>();
control.Animate($"{nameof(SetScaleAsync)}{control.Id}", v =>
{
if (double.IsNaN(v))
{
return;
}
control.Scale = v;
}, control.Scale, scale, 16, (uint)Abs(duration), easing, (v, b) => tcs.SetResult(b));
await tcs.Task;
}
19
Source : ApiCallAsync.cs
with MIT License
from AndyCW
with MIT License
from AndyCW
public async Task CallWithRetryAsync()
{
TaskCompletionSource<bool> retryTcs = new TaskCompletionSource<bool>();
bool result = true;
bool doRetry = true;
while (doRetry)
{
try
{
await perform().ConfigureAwait(false);
retryTcs.SetResult(result);
doRetry = false;
}
catch (Exception ex)
{
bool? mCancelled = RetryFunction?.Invoke(ex);
if (mCancelled.HasValue && mCancelled.Value)
{
// User has cancelled - break out of loop
Debug.WriteLine($"MAX RETRY COUNT EXCEEDED giving up Mds Api Call after exception: {ex.ToString()}");
retryTcs.SetException(ex);
throw ex;
}
else
{
Debug.WriteLine($"RETRYING Mds Api Call after exception: {ex.ToString()}");
await Task.Delay(RETRY_DELAY).ConfigureAwait(false);
}
}
}
return;
}
19
Source : ApiCallAsync.cs
with MIT License
from AndyCW
with MIT License
from AndyCW
public void OnSuccess(string s)
#endif
{
Debug.WriteLine($"SUCCESS result = {s}");
mTcs.SetResult(true);
}
19
Source : AsyncAutoResetEvent.cs
with MIT License
from andyalm
with MIT License
from andyalm
public void Set()
{
TaskCompletionSource<bool> toRelease = null;
lock (this.waiters)
{
if (this.waiters.Count > 0)
{
// Signal the first task in the waiters list.
toRelease = this.waiters.First.Value;
this.waiters.RemoveFirst();
}
else if (!this.isSignaled)
{
// No tasks are pending
this.isSignaled = true;
}
}
if (toRelease != null)
{
toRelease.SetResult(true);
}
}
19
Source : UIManager.cs
with MIT License
from angelsix
with MIT License
from angelsix
public Task ShowMessage(MessageBoxDialogViewModel viewModel)
{
// Create a task completion source
var tcs = new TaskCompletionSource<bool>();
// Run on UI thread
Application.Current.Dispatcher.Invoke(async () =>
{
try
{
// Show the dialog box
await new DialogMessageBox().ShowDialog(viewModel);
}
finally
{
// Flag we are done
tcs.SetResult(true);
}
});
// Return the task once complete
return tcs.Task;
}
19
Source : EventReceiver.cs
with MIT License
from angshuman
with MIT License
from angshuman
public Task ProcessEventsAsync(StoreEvent storeEvent)
{
var storeId = storeEvent.StoreId;
string operation = storeEvent.Operation;
var opId = storeEvent.OperationId;
var strict = storeEvent.Strict;
TaskCompletionSource<bool> tc = null;
if (opId != null) {
_completions.TryGetValue(opId, out tc);
}
try {
var data = storeEvent.Data;
switch (operation) {
case EventType.POST:
_storeProcessor.replacedert(storeId, data, strict);
break;
case EventType.PATCH_JSON:
_storeProcessor.PatchJson(storeId, data);
break;
case EventType.PATCH_TRIPLE:
var patch = (JObject)storeEvent.Data;
_storeProcessor.PatchTriple(storeId, patch);
break;
case EventType.DELETE:
_storeProcessor.Delete(storeId, data);
break;
default:
throw new InvalidOperationException($"Unknown operation {operation}");
}
tc?.SetResult(true);
} catch (Exception exception) {
tc?.SetException(exception);
} finally {
if (tc != null) {
_completions.Remove(opId, out _);
}
}
return Task.CompletedTask;
}
19
Source : AmqpConsumer.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private OnAttached HandleOpened(TaskCompletionSource<bool> tsc) => (link, attach) =>
{
if (validateSharedSubsLinkCapability)
{
Symbol[] remoteOfferedCapabilities = attach.OfferedCapabilities;
bool supported = false;
if (remoteOfferedCapabilities != null)
{
if (Array.Exists(remoteOfferedCapabilities, symbol => SymbolUtil.OPEN_CAPABILITY_SHARED_SUBS.Equals(symbol)))
{
supported = true;
}
}
if (!supported)
{
sharedSubsNotSupported = true;
if (info.IsDurable)
{
link.Detach(null);
}
else
{
link.Close();
}
}
}
if (IsClosePending(attach))
return;
tsc.SetResult(true);
};
19
Source : AmqpProducer.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private OnAttached HandleOpened(TaskCompletionSource<bool> tsc) => (link, attach) =>
{
if (IsClosePending(attach))
return;
tsc.SetResult(true);
};
19
Source : AmqpTemporaryDestination.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public Task Attach()
{
Attach result = new Attach
{
Source = CreateSource(),
Target = CreateTarget(),
SndSettleMode = SenderSettleMode.Unsettled,
RcvSettleMode = ReceiverSettleMode.First,
};
string linkDestinationName = "apache-nms:" + ((destination.IsTopic) ? CREATOR_TOPIC : CREATOR_QUEUE) + destination.Address;
var taskCompletionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
senderLink = new SenderLink(session.UnderlyingSession, linkDestinationName, result, (link, attach) =>
{
// Once our sender is opened we can read the updated address from the target address.
if (attach.Target is Target target && target.Address != null)
{
string oldDestinationAddress = destination.Address;
string destinationAddress = target.Address;
destination.Address = target.Address;
Tracer.Debug($"Updated temp destination to: {destinationAddress} from: {oldDestinationAddress}");
}
taskCompletionSource.SetResult(true);
});
senderLink.AddClosedCallback((sender, error) =>
{
NMSException exception = ExceptionSupport.GetException(error, $"Received attach response for Temporary creator link. Link = {destination}");
taskCompletionSource.TrySetException(exception);
});
return taskCompletionSource.Task;
}
19
Source : FailoverRequest.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private void WhenOffline(Exception exception)
{
if (FailureWhenOffline)
{
failoverProvider.RemoveFailoverRequest(this);
taskCompletionSource.TrySetException(exception);
}
else if (SucceedsWhenOffline)
{
failoverProvider.RemoveFailoverRequest(this);
taskCompletionSource.SetResult(true);
}
else
{
ScheduleTimeout();
Tracer.Debug($"Failover task held until connection recovered: {this}");
}
}
19
Source : UserDialogs.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
public async Task<bool> Confirm(string message, string buttonreplacedle, bool autoHide)
{
CheckNotificationExist();
var tcs = new TaskCompletionSource<bool>();
_notificationViewHidden = false;
UIApplication.SharedApplication.InvokeOnMainThread(() =>
{
_notificationView = new ARNotificationView(message, ARNotificationType.Confirm, buttonreplacedle, autoHide);
_notificationView.Show(() => tcs.TrySetResult(false), () => tcs.SetResult(true));
});
var result = await tcs.Task;
_notificationViewHidden = true;
return result;
}
19
Source : RabbitMessageBrokerClient.cs
with MIT License
from ArmandJ77
with MIT License
from ArmandJ77
public async Task<bool> Publish<T>(string topic, T message)
{
var tcs = new TaskCompletionSource<bool>();
var connectionTimeoutTask = Task.Delay(_options.Value.PublishConnectionTimeoutInSeconds * 1000);
var connectionTask = GetChannel(topic);
Task.WaitAny(connectionTask, connectionTimeoutTask);
if (!connectionTask.IsCompleted)
throw new Exception("Could not establish connection to message broker in the allowed timeout.");
var channel = connectionTask.Result;
channel.ExchangeDeclare(topic,
"topic",
durable: true
);
var bodyreplacedtring = JsonConvert.SerializeObject(message, Formatting.Indented);
var body = Encoding.UTF8.GetBytes(bodyreplacedtring);
channel.BasicPublish(topic,
"",
mandatory: true,
body: body
);
_defaultLogger.PublishedSucceeded(topic, bodyreplacedtring);
tcs.SetResult(true);
return await tcs.Task;
}
19
Source : RabbitMessageBusTests.cs
with MIT License
from ArmandJ77
with MIT License
from ArmandJ77
[Test]
public async Task Given_Subscribe_TestObjectTopic_Expect_TestObject_Response()
{
const string topic = "TestObjectTopic";
const string subscriptionId = "SubscribeToTestObject";
var message = TestObjectMother.GetBasicTestObject();
var result = await MessageBrokerClient.Publish(topic, message);
replacedert.That(result);
var subscriptionResponse = await MessageBrokerClient.Subscribe<TestObject>(topic,
subscriptionId, replacedertCallback, c => c.UseBasicQos());
static Task replacedertCallback(TestObject messageEvent)
{
var tcs = new TaskCompletionSource<bool>();
replacedert.That(TestObjectMother.GetBasicTestObject().Age, Is.EqualTo(messageEvent.Age));
replacedert.That(TestObjectMother.GetBasicTestObject().DateOfBirth, Is.EqualTo(messageEvent.DateOfBirth));
Stringreplacedert.AreEqualIgnoringCase(TestObjectMother.GetBasicTestObject().Name, messageEvent.Name);
tcs.SetResult(true);
return tcs.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 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 : MainWindow.xaml.cs
with MIT License
from Assistant
with MIT License
from Assistant
private async void LoadVersionsAsync()
{
try
{
var resp = await HttpClient.GetAsync(Utils.Constants.BeatModsVersions);
var body = await resp.Content.ReadreplacedtringAsync();
List<string> versions = JsonSerializer.Deserialize<string[]>(body).ToList();
resp = await HttpClient.GetAsync(Utils.Constants.BeatModsAlias);
body = await resp.Content.ReadreplacedtringAsync();
Dictionary<string, string[]> aliases = JsonSerializer.Deserialize<Dictionary<string, string[]>>(body);
Dispatcher.Invoke(() =>
{
GameVersion = GetGameVersion(versions, aliases);
GameVersionsBox.ItemsSource = versions;
GameVersionsBox.SelectedValue = GameVersion;
if (!string.IsNullOrEmpty(GameVersionOverride))
{
GameVersionsBox.Visibility = Visibility.Collapsed;
GameVersionsBoxOverride.Visibility = Visibility.Visible;
GameVersionsBoxOverride.Text = GameVersionOverride;
GameVersionsBoxOverride.IsEnabled = false;
}
if (!string.IsNullOrEmpty(GameVersion) && Properties.Settings.Default.Agreed)
{
Instance.ModsButton.IsEnabled = true;
}
});
VersionLoadStatus.SetResult(true);
}
catch (Exception e)
{
Dispatcher.Invoke(() =>
{
GameVersionsBox.IsEnabled = false;
MessageBox.Show($"{Application.Current.FindResource("MainWindow:GameVersionLoadFailed")}\n{e}");
});
VersionLoadStatus.SetResult(false);
}
}
19
Source : Program.cs
with Apache License 2.0
from asynkron
with Apache License 2.0
from asynkron
public Task ReceiveAsync(IContext context)
{
switch (context.Message)
{
case Start s:
_targetPid = s.Sender;
SendBatch(context);
break;
case Msg m:
_messageCount--;
if (_messageCount <= 0) _wgStop.SetResult(true);
else context.Send(_targetPid, m);
break;
}
return Task.CompletedTask;
}
19
Source : TestActors.cs
with Apache License 2.0
from asynkron
with Apache License 2.0
from asynkron
public Task ReceiveAsync(IContext context)
{
switch (context.Message)
{
case Start s:
SendBatch(context, s.Sender);
break;
case Msg m:
_batch--;
if (_batch > 0) break;
if (!SendBatch(context, m.Sender)) _wgStop.SetResult(true);
break;
}
return Task.CompletedTask;
}
19
Source : PartitionControllerCore.cs
with MIT License
from Azure
with MIT License
from Azure
private async Task RemoveLeaseAsync(DoreplacedentServiceLease lease)
{
if (!this.currentlyOwnedParreplacedions.TryRemove(lease.CurrentLeaseToken, out TaskCompletionSource<bool> worker))
{
return;
}
try
{
await this.leaseManager.ReleaseAsync(lease).ConfigureAwait(false);
await this.monitor.NotifyLeaseReleaseAsync(lease.CurrentLeaseToken);
}
catch (Exception ex)
{
await this.monitor.NotifyErrorAsync(lease.CurrentLeaseToken, ex);
DefaultTrace.TraceWarning("Lease with token {0}: failed to remove lease", lease.CurrentLeaseToken);
}
finally
{
worker.SetResult(false);
}
}
19
Source : AsyncAutoResetEvent.cs
with MIT License
from Azure
with MIT License
from Azure
public void Set()
{
TaskCompletionSource<bool> toRelease = null;
lock (_waits)
{
if (_waits.Count > 0)
{
toRelease = _waits.Dequeue();
}
else if (!_signaled)
{
_signaled = true;
}
}
if (toRelease != null)
{
toRelease.SetResult(true);
}
}
19
Source : BackOffPolicy.cs
with MIT License
from Azure
with MIT License
from Azure
public async Task<bool> CallProbeWithBackOffAsync(Func<Task<bool>> probe, Func<int, TimeSpan> getRetryDelay)
{
bool calledProbeOnce = false;
bool probeSuccess = false;
var myTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
do
{
// ensure only one caller will be selected to call probing func
var ongoingProbeTcs = Interlocked.CompareExchange(ref _currentProbeTcs, myTcs, null);
if (ongoingProbeTcs == null)
{
// initiate the probe and indicate its result to others
Task<bool> probeTask = null;
bool awaitProbeTask = false;
try
{
Debug.replacedert(!calledProbeOnce);
calledProbeOnce = true;
probeTask = probe();
using (CancellationTokenSource delayCts = new CancellationTokenSource())
{
var delayTask = Task.Delay(getRetryDelay(_currentRetryCount++), delayCts.Token);
await Task.WhenAny(delayTask, probeTask);
// Handle success, timeout, and failure appropriately
if (//probeTask.IsCompletedSuccessfully in .NET Standard 2.1
probeTask.Status == TaskStatus.RanToCompletion && !probeTask.IsFaulted && !probeTask.IsCanceled
&& probeTask.Result)
{
// probe is successful
delayCts.Cancel();
probeSuccess = true;
}
else if (delayTask.IsCompleted) //delayTask.IsCompletedSuccessfully
{
// probe timeout
// make sure we still await for the probe task after indicating the failure to others
awaitProbeTask = true;
}
else
{
// probe failed
// make sure we still await for the probe task
awaitProbeTask = true;
// after waiting for the current backoff time and indicating failure to others
await delayTask;
}
}
}
finally
{
Interlocked.Exchange(ref _currentProbeTcs, null);
// indicate the result to others
myTcs.SetResult(probeSuccess);
}
// take care of unfinished probe task
if (awaitProbeTask)
{
probeSuccess = await probeTask;
}
}
// wait for the shared probe's result and try ourselves in case of the shared probe success
else if (await ongoingProbeTcs.Task)
{
Debug.replacedert(!calledProbeOnce);
calledProbeOnce = true;
probeSuccess = await probe();
}
}
while (!calledProbeOnce);
if (probeSuccess)
{
// each successful probe call resets the retry counter
_currentRetryCount = 0;
}
return probeSuccess;
}
19
Source : SameSvcConnAfterClientConnectionClosedHub.cs
with MIT License
from Azure
with MIT License
from Azure
public override Task OnDisconnectedAsync(Exception exception)
{
base.OnDisconnectedAsync(exception);
s_disconnectedTcs?.SetResult(true);
return Task.CompletedTask;
}
19
Source : ServiceConnectionContainerBaseTests.cs
with MIT License
from Azure
with MIT License
from Azure
public Task WriteAsync(ServiceMessage serviceMessage)
{
if (RuntimeServicePingMessage.IsFin(serviceMessage))
{
_offline.SetResult(true);
}
if (RuntimeServicePingMessage.IsGetServers(serviceMessage))
{
_serversPing.SetResult(true);
}
return Task.CompletedTask;
}
19
Source : PublisherServiceEventsTests.cs
with MIT License
from Azure
with MIT License
from Azure
[Theory]
[InlineData(10)]
[InlineData(4455)]
[InlineData(262345)]
public async Task TestPublishPublisherEventAndReceiveMultipleAsync(int total) {
var bus = _factory.Resolve<ISubscriberMessageProcessor>();
var client = _factory.Resolve<IPublisherServiceEvents>();
var endpointId = "testid";
var expected = new MonitoredItemMessageModel {
DataSetWriterId = "testid",
EndpointId = endpointId,
DisplayName = "holla",
NodeId = "nodeid",
SourceTimestamp = DateTime.UtcNow,
Timestamp = DateTime.UtcNow,
Value = 234234
};
var result = new TaskCompletionSource<bool>();
var counter = 0;
await using (await client.NodePublishSubscribeByEndpointAsync(endpointId, ev => {
counter++;
if (counter == total) {
result.SetResult(true);
}
return Task.CompletedTask;
})) {
for (var i = 0; i < total; i++) {
await bus.HandleSampleAsync(expected);
}
await Task.WhenAny(result.Task, Task.Delay(10000));
replacedert.True(result.Task.IsCompleted, $"{counter} received instead of {total}");
}
}
19
Source : RegistryServiceEventsTests.cs
with MIT License
from Azure
with MIT License
from Azure
[Theory]
[InlineData(10)]
[InlineData(100)]
[InlineData(678)]
public async Task TestPublishPublisherEventAndReceiveMultipleAsync(int total) {
var bus = _factory.Resolve<IEventBus>();
var client = _factory.Resolve<IRegistryServiceEvents>();
var expected = new PublisherEventModel {
Publisher = new PublisherModel {
SiteId = "TestSite",
LogLevel = IIoT.OpcUa.Registry.Models.TraceLogLevel.Verbose
}
};
var result = new TaskCompletionSource<bool>();
var counter = 0;
await using (await client.SubscribePublisherEventsAsync(ev => {
counter++;
if (counter == total) {
result.SetResult(true);
}
return Task.CompletedTask;
})) {
for (var i = 0; i < total; i++) {
await bus.PublishAsync(expected);
}
await Task.WhenAny(result.Task, Task.Delay(5000));
replacedert.True(result.Task.IsCompleted);
}
}
19
Source : RegistryServiceEventsTests.cs
with MIT License
from Azure
with MIT License
from Azure
[Theory]
[InlineData(10)]
[InlineData(55)]
[InlineData(375)]
public async Task TestPublishDiscovererEventAndReceiveMultipleAsync(int total) {
var bus = _factory.Resolve<IEventBus>();
var client = _factory.Resolve<IRegistryServiceEvents>();
var expected = new DiscovererEventModel {
Discoverer = new DiscovererModel {
SiteId = "TestSite",
LogLevel = IIoT.OpcUa.Registry.Models.TraceLogLevel.Verbose
}
};
var result = new TaskCompletionSource<bool>();
var counter = 0;
await using (await client.SubscribeDiscovererEventsAsync(ev => {
counter++;
if (counter == total) {
result.SetResult(true);
}
return Task.CompletedTask;
})) {
for (var i = 0; i < total; i++) {
await bus.PublishAsync(expected);
}
await Task.WhenAny(result.Task, Task.Delay(5000));
replacedert.True(result.Task.IsCompleted);
}
}
19
Source : RegistryServiceEventsTests.cs
with MIT License
from Azure
with MIT License
from Azure
[Theory]
[InlineData(10)]
[InlineData(100)]
[InlineData(4634)]
public async Task TestPublishSupervisorEventAndReceiveMultipleAsync(int total) {
var bus = _factory.Resolve<IEventBus>();
var client = _factory.Resolve<IRegistryServiceEvents>();
var expected = new SupervisorEventModel {
Supervisor = new SupervisorModel {
SiteId = "azagfff",
LogLevel = IIoT.OpcUa.Registry.Models.TraceLogLevel.Verbose
}
};
var result = new TaskCompletionSource<bool>();
var counter = 0;
await using (await client.SubscribeSupervisorEventsAsync(ev => {
counter++;
if (counter == total) {
result.SetResult(true);
}
return Task.CompletedTask;
})) {
for (var i = 0; i < total; i++) {
await bus.PublishAsync(expected);
}
await Task.WhenAny(result.Task, Task.Delay(5000));
replacedert.True(result.Task.IsCompleted);
}
}
19
Source : RegistryServiceEventsTests.cs
with MIT License
from Azure
with MIT License
from Azure
[Theory]
[InlineData(10)]
[InlineData(100)]
[InlineData(4634)]
public async Task TestPublishApplicationEventAndReceiveMultipleAsync(int total) {
var bus = _factory.Resolve<IEventBus>();
var client = _factory.Resolve<IRegistryServiceEvents>();
var expected = new ApplicationEventModel {
Application = new ApplicationInfoModel {
SiteId = "TestSigfsdfg ff",
ApplicationType = IIoT.OpcUa.Core.Models.ApplicationType.Client,
NotSeenSince = DateTime.UtcNow,
Capabilities = new HashSet<string> { "ag", "sadf", "" },
}
};
var result = new TaskCompletionSource<bool>();
var counter = 0;
await using (await client.SubscribeApplicationEventsAsync(ev => {
counter++;
if (counter == total) {
result.SetResult(true);
}
return Task.CompletedTask;
})) {
for (var i = 0; i < total; i++) {
await bus.PublishAsync(expected);
}
await Task.WhenAny(result.Task, Task.Delay(5000));
replacedert.True(result.Task.IsCompleted);
}
}
19
Source : RegistryServiceEventsTests.cs
with MIT License
from Azure
with MIT License
from Azure
[Theory]
[InlineData(10)]
[InlineData(100)]
[InlineData(46340)]
public async Task TestPublishEndpointEventAndReceiveMultipleAsync(int total) {
var bus = _factory.Resolve<IEventBus>();
var client = _factory.Resolve<IRegistryServiceEvents>();
var expected = new EndpointEventModel {
Endpoint = new EndpointInfoModel {
ApplicationId = "TestSigfsdfg ff",
ActivationState = IIoT.OpcUa.Registry.Models.EndpointActivationState.ActivatedAndConnected,
NotSeenSince = DateTime.UtcNow
}
};
var result = new TaskCompletionSource<bool>();
var counter = 0;
await using (await client.SubscribeEndpointEventsAsync(ev => {
counter++;
if (counter == total) {
result.SetResult(true);
}
return Task.CompletedTask;
})) {
for (var i = 0; i < total; i++) {
await bus.PublishAsync(expected);
}
await Task.WhenAny(result.Task, Task.Delay(5000));
replacedert.True(result.Task.IsCompleted);
}
}
19
Source : RegistryServiceEventsTests.cs
with MIT License
from Azure
with MIT License
from Azure
[Theory]
[InlineData(10)]
[InlineData(100)]
public async Task TestPublishGatewayEventAndReceiveMultipleAsync(int total) {
var bus = _factory.Resolve<IEventBus>();
var client = _factory.Resolve<IRegistryServiceEvents>();
var expected = new GatewayEventModel {
Gateway = new GatewayModel {
SiteId = "TestSigfsdfg ff",
}
};
var result = new TaskCompletionSource<bool>();
var counter = 0;
await using (await client.SubscribeGatewayEventsAsync(ev => {
counter++;
if (counter == total) {
result.SetResult(true);
}
return Task.CompletedTask;
})) {
for (var i = 0; i < total; i++) {
await bus.PublishAsync(expected);
}
await Task.WhenAny(result.Task, Task.Delay(5000));
replacedert.True(result.Task.IsCompleted);
}
}
19
Source : RegistryServiceEventsTests.cs
with MIT License
from Azure
with MIT License
from Azure
[Theory]
[InlineData(10)]
[InlineData(100)]
[InlineData(678)]
public async Task TestPublishDiscoveryProgressAndReceiveMultipleAsync(int total) {
var bus = _factory.Resolve<IEventBus>();
var client = _factory.Resolve<IRegistryServiceEvents>();
var discovererId = "TestDiscoverer1";
var expected = new DiscoveryProgressModel {
DiscovererId = discovererId,
Discovered = 55,
EventType = IIoT.OpcUa.Registry.Models.DiscoveryProgressType.NetworkScanFinished,
TimeStamp = DateTime.UtcNow
};
var result = new TaskCompletionSource<bool>();
var counter = 0;
await using (await client.SubscribeDiscoveryProgressByDiscovererIdAsync(
discovererId, ev => {
counter++;
if (counter == total) {
result.SetResult(true);
}
return Task.CompletedTask;
})) {
for (var i = 0; i < total; i++) {
await bus.PublishAsync(expected);
}
await Task.WhenAny(result.Task, Task.Delay(5000));
replacedert.True(result.Task.IsCompleted);
}
}
19
Source : MetricsWorkerTest.cs
with MIT License
from Azure
with MIT License
from Azure
[Fact]
public async Task TestBasicUploading()
{
/* Setup mocks */
var scraper = new Mock<IMetricsScraper>();
var storage = new Mock<IMetricsStorage>();
storage.Setup(s => s.GetAllMetricsAsync()).ReturnsAsync(Enumerable.Empty<Metric>());
TaskCompletionSource<object> uploadStarted = new TaskCompletionSource<object>();
TaskCompletionSource<bool> finishUpload = new TaskCompletionSource<bool>();
var uploader = new Mock<IMetricsPublisher>();
IEnumerable<Metric> uploadedData = Enumerable.Empty<Metric>();
uploader.Setup(u => u.PublishAsync(It.IsAny<IEnumerable<Metric>>(), It.IsAny<CancellationToken>())).Callback((Action<IEnumerable<Metric>, CancellationToken>)((data, __) =>
{
uploadedData = data;
uploadStarted.SetResult(null);
})).Returns(finishUpload.Task);
MetricsWorker worker = new MetricsWorker(scraper.Object, storage.Object, uploader.Object);
/* test */
Task workerTask = worker.Upload(CancellationToken.None);
await uploadStarted.Task;
uploadedData.ToList();
replacedert.Equal(1, uploader.Invocations.Count);
replacedert.Single(storage.Invocations.Where(i => i.Method.Name == "GetAllMetricsAsync"));
replacedert.Empty(storage.Invocations.Where(i => i.Method.Name == "RemoveAllReturnedMetricsAsync"));
finishUpload.SetResult(true);
replacedert.Single(storage.Invocations.Where(i => i.Method.Name == "GetAllMetricsAsync"));
replacedert.Single(storage.Invocations.Where(i => i.Method.Name == "RemoveAllReturnedMetricsAsync"));
}
19
Source : MetricsWorkerTest.cs
with MIT License
from Azure
with MIT License
from Azure
[Fact]
public async Task TestNoOverlap()
{
/* Setup mocks */
TaskCompletionSource<bool> scrapeTaskSource = new TaskCompletionSource<bool>();
TaskCompletionSource<bool> uploadTaskSource = new TaskCompletionSource<bool>();
var scraper = new Mock<IMetricsScraper>();
scraper.Setup(s => s.ScrapeEndpointsAsync(CancellationToken.None)).Returns(async () =>
{
await scrapeTaskSource.Task;
return this.PrometheusMetrics(Enumerable.Range(1, 10).Select(i => ($"module_{i}", 1.0)).ToArray());
});
var storage = new Mock<IMetricsStorage>();
var uploader = new Mock<IMetricsPublisher>();
uploader.Setup(u => u.PublishAsync(It.IsAny<IEnumerable<Metric>>(), It.IsAny<CancellationToken>())).Returns(async () => await uploadTaskSource.Task);
MetricsWorker worker = new MetricsWorker(scraper.Object, storage.Object, uploader.Object);
/* test scraper first */
var scrapeTask = worker.Scrape(CancellationToken.None);
await Task.Delay(1);
var uploadTask = worker.Upload(CancellationToken.None);
await Task.Delay(1);
uploadTaskSource.SetResult(true);
await Task.Delay(1);
replacedert.False(scrapeTask.IsCompleted);
replacedert.False(uploadTask.IsCompleted);
scrapeTaskSource.SetResult(true);
await Task.Delay(1);
await Task.WhenAll(scrapeTask, uploadTask);
/* test uploader first */
scrapeTaskSource = new TaskCompletionSource<bool>();
uploadTaskSource = new TaskCompletionSource<bool>();
uploadTask = worker.Upload(CancellationToken.None);
await Task.Delay(1);
scrapeTask = worker.Scrape(CancellationToken.None);
await Task.Delay(1);
scrapeTaskSource.SetResult(true);
await Task.Delay(1);
replacedert.False(scrapeTask.IsCompleted);
replacedert.False(uploadTask.IsCompleted);
uploadTaskSource.SetResult(true);
await Task.Delay(1);
await Task.WhenAll(scrapeTask, uploadTask);
}
19
Source : AmqpWebSocketListener.cs
with MIT License
from Azure
with MIT License
from Azure
public async Task ProcessWebSocketRequestAsync(WebSocket webSocket, Option<EndPoint> localEndPoint, EndPoint remoteEndPoint, string correlationId, X509Certificate2 clientCert, IList<X509Certificate2> clientCertChain, IAuthenticator proxyAuthenticator = null)
{
try
{
var taskCompletion = new TaskCompletionSource<bool>();
string localEndpointValue = localEndPoint.Expect(() => new ArgumentNullException(nameof(localEndPoint))).ToString();
ServerWebSocketTransport transport;
if ((clientCert != null) && (clientCertChain != null))
{
transport = new ServerWebSocketTransport(
webSocket,
localEndpointValue,
remoteEndPoint.ToString(),
correlationId,
clientCert,
clientCertChain,
proxyAuthenticator ?? this.authenticator,
this.clientCredentialsFactory);
}
else
{
transport = new ServerWebSocketTransport(
webSocket,
localEndpointValue,
remoteEndPoint.ToString(),
correlationId);
}
transport.Open();
var args = new TransportAsyncCallbackArgs { Transport = transport, CompletedSynchronously = false };
this.OnTransportAccepted(args);
Events.EstablishedConnection(correlationId);
transport.Closed += (sender, eventArgs) => { taskCompletion.SetResult(true); };
// wait until websocket is closed
await taskCompletion.Task;
}
catch (Exception ex) when (!ex.IsFatal())
{
Events.FailedAcceptWebSocket(correlationId, ex);
throw;
}
}
19
Source : DeviceMessageHandler.cs
with MIT License
from Azure
with MIT License
from Azure
public async Task ProcessMessageFeedbackAsync(string messageId, FeedbackStatus feedbackStatus)
{
if (string.IsNullOrWhiteSpace(messageId))
{
Events.MessageFeedbackWithNoMessageId(this.Idenreplacedy);
return;
}
Events.MessageFeedbackReceived(this.Idenreplacedy, messageId, feedbackStatus);
if (this.messageTaskCompletionSources.TryRemove(messageId, out TaskCompletionSource<bool> taskCompletionSource))
{
if (feedbackStatus == FeedbackStatus.Complete)
{
// TaskCompletionSource.SetResult causes the continuation of the underlying task
// to happen on the same thread. So calling Task.Yield to let go of the current thread
// That way the underlying task will be scheduled to complete asynchronously on a different thread
await Task.Yield();
taskCompletionSource.SetResult(true);
}
else
{
taskCompletionSource.SetException(new EdgeHubMessageRejectedException($"Message not completed by client {this.Idenreplacedy.Id}"));
}
}
else if (this.c2dMessageTaskCompletionSources.TryRemove(messageId, out bool value) && value)
{
Events.ReceivedC2DFeedbackMessage(this.Idenreplacedy, messageId);
Option<ICloudProxy> cloudProxy = await this.connectionManager.GetCloudConnection(this.Idenreplacedy.Id);
await cloudProxy.ForEachAsync(cp => cp.SendFeedbackMessageAsync(messageId, feedbackStatus));
}
else
{
Events.UnknownFeedbackMessage(this.Idenreplacedy, messageId, feedbackStatus);
}
}
19
Source : MqttBrokerConnector.cs
with MIT License
from Azure
with MIT License
from Azure
void ConfirmPublished(object sender, MqttMsgPublishedEventArgs e)
{
lock (this.guard)
{
if (this.pendingAcks.TryRemove(e.MessageId, out TaskCompletionSource<bool> tcs))
{
tcs.SetResult(e.IsPublished);
}
else
{
Events.UnknownMessageId(e.MessageId);
}
}
}
19
Source : BrokeredCloudProxyDispatcher.cs
with MIT License
from Azure
with MIT License
from Azure
void HandleRpcAck(string ackedGuid)
{
if (!Guid.TryParse(ackedGuid, out var guid))
{
Events.CannotParseGuid(ackedGuid);
return;
}
if (this.pendingRpcs.TryRemove(guid, out var tsc))
{
tsc.SetResult(true);
}
else
{
Events.CannotFindGuid(ackedGuid);
}
}
See More Examples