System.Threading.Tasks.TaskCompletionSource.SetResult(bool)

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 7

19 Source : EchoActor.cs
with Apache License 2.0
from Blind-Striker

public Task ReceiveAsync(IContext context)
        {
            var contextSelf = context.Self;

            switch (context.Message)
            {
                case PiNumber _:
                    _calculationCount--;

                    if (_calculationCount == 0)
                    {
                        _taskCompletionSource.SetResult(true);
                    }
                    break;
            }

            return Actor.Done;
        }

19 Source : ClientActor.cs
with Apache License 2.0
from Blind-Striker

public Task ReceiveAsync(IContext context)
        {
            var message = context.Message;

            switch (message)
            {
                case Messages.Msg _:
                    _received++;
                    if (_sent < _repeat)
                    {
                        _actor.Tell(message);
                        _sent++;
                    }
                    else if (_received >= _repeat)
                    {
                        _latch.SetResult(true);
                    }
                    return Actor.Done;
                case Messages.Run _:
                    var msg = new Messages.Msg {Sender = context.Self};
                    for (var i = 0; i < Math.Min(1000, _repeat); i++)
                    {
                        _actor.Tell(msg);
                        _sent++;
                    }
                    return Actor.Done;
                case Messages.Started started:
                    started.Sender.Tell(message);
                    return Actor.Done;
            }

            return Actor.Done;
        }

19 Source : YoutubeDLProcess.cs
with BSD 3-Clause "New" or "Revised" License
from Bluegrams

public async Task<int> RunAsync(string[] urls, OptionSet options,
            CancellationToken ct, IProgress<DownloadProgress> progress = null)
        {
            var tcs = new TaskCompletionSource<int>();
            var process = new Process();
            var startInfo = new ProcessStartInfo()
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true

            };
            if (!String.IsNullOrEmpty(PythonPath))
            {
                startInfo.FileName = PythonPath;
                startInfo.Arguments = $"\"{ExecutablePath}\" {ConvertToArgs(urls, options)}";
            }
            else
            {
                startInfo.FileName = ExecutablePath;
                startInfo.Arguments = ConvertToArgs(urls, options);
            }
            process.EnableRaisingEvents = true;
            process.StartInfo = startInfo;
            var tcsOut = new TaskCompletionSource<bool>();
            process.OutputDataReceived += (o, e) =>
            {
                if (e.Data == null)
                {
                    tcsOut.SetResult(true);
                    return;
                }
                Match match;
                if ((match = rgxProgress.Match(e.Data)).Success)
                {
                    if (match.Groups.Count > 1 && match.Groups[1].Length > 0)
                    {
                        float progValue = float.Parse(match.Groups[1].ToString(), CultureInfo.InvariantCulture) / 100.0f;
                        Group totalGroup = match.Groups["total"];
                        string total = totalGroup.Success ? totalGroup.Value : null;
                        Group speedGroup = match.Groups["speed"];
                        string speed = speedGroup.Success ? speedGroup.Value : null;
                        Group etaGroup = match.Groups["eta"];
                        string eta = etaGroup.Success ? etaGroup.Value : null;
                        progress?.Report(
                            new DownloadProgress(
                                DownloadState.Downloading, progress: progValue, totalDownloadSize: total, downloadSpeed: speed, eta: eta
                            )
                        );
                    }
                    else
                    {
                        progress?.Report(new DownloadProgress(DownloadState.Downloading));
                    }
                }
                else if ((match = rgxPost.Match(e.Data)).Success)
                {
                    progress?.Report(new DownloadProgress(DownloadState.PostProcessing, 1));
                }
                else if ((match = rgxPlaylist.Match(e.Data)).Success)
                {
                    var index = int.Parse(match.Groups[1].Value);
                    progress?.Report(new DownloadProgress(DownloadState.PreProcessing, index: index));
                }
                Debug.WriteLine("[youtube-dl] " + e.Data);
                OutputReceived?.Invoke(this, e);
            };
            var tcsError = new TaskCompletionSource<bool>();
            process.ErrorDataReceived += (o, e) =>
            {
                if (e.Data == null)
                {
                    tcsError.SetResult(true);
                    return;
                }
                Debug.WriteLine("[youtube-dl ERROR] " + e.Data);
                progress?.Report(new DownloadProgress(DownloadState.Error, data: e.Data));
                ErrorReceived?.Invoke(this, e);
            };
            process.Exited += async (sender, args) =>
            {
                // Wait for output and error streams to finish
                await tcsOut.Task;
                await tcsError.Task;
                tcs.TrySetResult(process.ExitCode);
                process.Dispose();
            };
            ct.Register(() =>
            {
                if (!tcs.Task.IsCompleted)
                    tcs.TrySetCanceled();
                try { if (!process.HasExited) process.KillTree(); }
                catch { }
            });
            Debug.WriteLine("[youtube-dl] Arguments: " + process.StartInfo.Arguments);
            if (!process.Start())
                tcs.TrySetException(new InvalidOperationException("Failed to start youtube-dl process."));
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            progress?.Report(new DownloadProgress(DownloadState.PreProcessing));
            return await tcs.Task;
        }

19 Source : SemaphoreQueue.cs
with MIT License
from BookBeat

public Task WaitAsync(CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource<bool>();
            _queue.Enqueue(tcs);
            _semapreplaced.WaitAsync(cancellationToken).ContinueWith(t =>
            {
                if (_queue.TryDequeue(out var popped))
                {
                    if(t.IsCanceled)
                        popped.SetCanceled();
                    else
                        popped.SetResult(true);
                }
                    
            });
            return tcs.Task;
        }

19 Source : Exchange.cs
with MIT License
from bording

void Handle_DeclareOk(object tcs, ReadOnlySequence<byte> arguments, Exception exception)
        {
            var declareOk = (TaskCompletionSource<bool>)tcs;

            if (exception != null)
            {
                declareOk.SetException(exception);
            }
            else
            {
                declareOk.SetResult(true);
            }
        }

19 Source : Exchange.cs
with MIT License
from bording

void Handle_DeleteOk(object tcs, ReadOnlySequence<byte> arguments, Exception exception)
        {
            var deleteOk = (TaskCompletionSource<bool>)tcs;

            if (exception != null)
            {
                deleteOk.SetException(exception);
            }
            else
            {
                deleteOk.SetResult(true);
            }
        }

19 Source : Exchange.cs
with MIT License
from bording

void Handle_BindOk(object tcs, ReadOnlySequence<byte> arguments, Exception exception)
        {
            var bindOk = (TaskCompletionSource<bool>)tcs;

            if (exception != null)
            {
                bindOk.SetException(exception);
            }
            else
            {
                bindOk.SetResult(true);
            }
        }

19 Source : Exchange.cs
with MIT License
from bording

void Handle_UnbindOk(object tcs, ReadOnlySequence<byte> arguments, Exception exception)
        {
            var unbindOk = (TaskCompletionSource<bool>)tcs;

            if (exception != null)
            {
                unbindOk.SetException(exception);
            }
            else
            {
                unbindOk.SetResult(true);
            }
        }

19 Source : Basic.cs
with MIT License
from bording

void Handle_QosOk(object tcs, ReadOnlySequence<byte> arguments, Exception exception)
        {
            var qosOk = (TaskCompletionSource<bool>)tcs;

            if (exception != null)
            {
                qosOk.SetException(exception);
            }
            else
            {
                qosOk.SetResult(true);
            }
        }

19 Source : Basic.cs
with MIT License
from bording

void Handle_RecoverOk(object tcs, ReadOnlySequence<byte> arguments, Exception exception)
        {
            var recoverOk = (TaskCompletionSource<bool>)tcs;

            if (exception != null)
            {
                recoverOk.SetException(exception);
            }
            else
            {
                recoverOk.SetResult(true);
            }
        }

19 Source : Connection.cs
with MIT License
from bording

async Task HandleIncomingMethod(uint method, ReadOnlySequence<byte> arguments)
        {
            switch (method)
            {
                case Method.Connection.Start:
                    await Handle_Start(arguments);
                    break;

                case Method.Connection.Tune:
                    await Handle_Tune(arguments);
                    break;

                case Method.Connection.Close:
                    await Handle_Close(arguments);
                    break;

                case Method.Connection.OpenOk:
                    openOk.SetResult(true);
                    break;

                case Method.Connection.CloseOk:
                    closeOk.SetResult(true);
                    break;
            }
        }

19 Source : Channel.cs
with MIT License
from bording

void Handle_OpenOk(object tcs, ReadOnlySequence<byte> arguments, Exception exception)
        {
            var openOk = (TaskCompletionSource<bool>)tcs;

            if (exception != null)
            {
                openOk.SetException(exception);
            }
            else
            {
                IsOpen = true;
                openOk.SetResult(true);
            }
        }

19 Source : Channel.cs
with MIT License
from bording

void Handle_CloseOk(object tcs, ReadOnlySequence<byte> arguments, Exception exception)
        {
            var closeOk = (TaskCompletionSource<bool>)tcs;

            if (exception != null)
            {
                closeOk.SetException(exception);
            }
            else
            {
                IsOpen = false;
                closeOk.SetResult(true);
            }
        }

19 Source : TumblerServiceBase.cs
with MIT License
from BreezeHub

protected void Stopped()
		{
			_Stopping.SetResult(true);
		}

19 Source : DeviceNotificationsService_iOS.cs
with MIT License
from brminnick

public Task<bool?> AreNotificationEnabled() => MainThread.InvokeOnMainThreadAsync(() =>
        {
            var tcs = new TaskCompletionSource<bool?>();

            UNUserNotificationCenter.Current.GetNotificationSettings(notificationSettings =>
            {
                var hasAlertNeverBeenRequested = notificationSettings.AlertSetting is UNNotificationSetting.NotSupported;
                var hasBadgeNeverBeenRequested = notificationSettings.BadgeSetting is UNNotificationSetting.NotSupported;
                var hreplacedoundsNeverBeenRequested = notificationSettings.SoundSetting is UNNotificationSetting.NotSupported;

                var isAlertEnabled = notificationSettings.AlertSetting is UNNotificationSetting.Enabled;
                var isBadgeEnabled = notificationSettings.BadgeSetting is UNNotificationSetting.Enabled;
                var isSoundsEnabled = notificationSettings.SoundSetting is UNNotificationSetting.Enabled;

                if (isAlertEnabled || isBadgeEnabled || isSoundsEnabled)
                    tcs.SetResult(true);
                else if (hasAlertNeverBeenRequested && hasBadgeNeverBeenRequested && hreplacedoundsNeverBeenRequested)
                    tcs.SetResult(null);
                else
                    tcs.SetResult(false);
            });

            return tcs.Task;
        });

19 Source : BackgroundFetchServiceTests.cs
with MIT License
from brminnick

[Test]
		public async Task NotifyTrendingRepositoriesTest_NotLoggedIn()
		{
			//Arrange
			var scheduleNotifyTrendingRepositoriesCompletedTCS = new TaskCompletionSource<bool>();
			BackgroundFetchService.ScheduleNotifyTrendingRepositoriesCompleted += HandleScheduleNotifyTrendingRepositoriesCompleted;

			var backgroundFetchService = ServiceCollection.ServiceProvider.GetRequiredService<BackgroundFetchService>();

			//Act
			backgroundFetchService.TryScheduleNotifyTrendingRepositories(CancellationToken.None);

			var result = await scheduleNotifyTrendingRepositoriesCompletedTCS.Task.ConfigureAwait(false);

			//replacedert
			replacedert.IsFalse(result);

			void HandleScheduleNotifyTrendingRepositoriesCompleted(object? sender, bool e)
			{
				BackgroundFetchService.ScheduleNotifyTrendingRepositoriesCompleted -= HandleScheduleNotifyTrendingRepositoriesCompleted;
				scheduleNotifyTrendingRepositoriesCompletedTCS.SetResult(e);
			}
		}

19 Source : BackgroundFetchServiceTests.cs
with MIT License
from brminnick

[Test]
		public async Task NotifyTrendingRepositoriesTest_DemoUser()
		{
			//Arrange
			var scheduleNotifyTrendingRepositoriesCompletedTCS = new TaskCompletionSource<bool>();
			BackgroundFetchService.ScheduleNotifyTrendingRepositoriesCompleted += HandleScheduleNotifyTrendingRepositoriesCompleted;

			var gitHubAuthenticationService = ServiceCollection.ServiceProvider.GetRequiredService<GitHubAuthenticationService>();
			await gitHubAuthenticationService.ActivateDemoUser().ConfigureAwait(false);

			var gitHubUserService = ServiceCollection.ServiceProvider.GetRequiredService<GitHubUserService>();
			var backgroundFetchService = ServiceCollection.ServiceProvider.GetRequiredService<BackgroundFetchService>();

			//Act
			backgroundFetchService.TryScheduleNotifyTrendingRepositories(CancellationToken.None);

			var result = await scheduleNotifyTrendingRepositoriesCompletedTCS.Task.ConfigureAwait(false);

			//replacedert
			replacedert.IsTrue(gitHubUserService.IsDemoUser);
			replacedert.IsFalse(gitHubUserService.IsAuthenticated);
			replacedert.IsFalse(result);

			void HandleScheduleNotifyTrendingRepositoriesCompleted(object? sender, bool e)
			{
				BackgroundFetchService.ScheduleNotifyTrendingRepositoriesCompleted -= HandleScheduleNotifyTrendingRepositoriesCompleted;
				scheduleNotifyTrendingRepositoriesCompletedTCS.SetResult(e);
			}
		}

19 Source : BackgroundFetchServiceTests.cs
with MIT License
from brminnick

[Test]
		public async Task NotifyTrendingRepositoriesTest_AuthenticatedUser()
		{
			//Arrange
			bool wreplacedcheduledSuccessfully_First, wreplacedcheduledSuccessfully_Second;
			var scheduleNotifyTrendingRepositoriesCompletedTCS = new TaskCompletionSource<bool>();
			BackgroundFetchService.ScheduleNotifyTrendingRepositoriesCompleted += HandleScheduleNotifyTrendingRepositoriesCompleted;

			var gitHubUserService = ServiceCollection.ServiceProvider.GetRequiredService<GitHubUserService>();
			var backgroundFetchService = ServiceCollection.ServiceProvider.GetRequiredService<BackgroundFetchService>();
			var gitHubGraphQLApiService = ServiceCollection.ServiceProvider.GetRequiredService<GitHubGraphQLApiService>();

			await AuthenticateUser(gitHubUserService, gitHubGraphQLApiService).ConfigureAwait(false);

			//Act
			wreplacedcheduledSuccessfully_First = backgroundFetchService.TryScheduleNotifyTrendingRepositories(CancellationToken.None);
			wreplacedcheduledSuccessfully_Second = backgroundFetchService.TryScheduleNotifyTrendingRepositories(CancellationToken.None);

			var result = await scheduleNotifyTrendingRepositoriesCompletedTCS.Task.ConfigureAwait(false);

			//replacedert
			replacedert.IsTrue(wreplacedcheduledSuccessfully_First);
			replacedert.IsFalse(wreplacedcheduledSuccessfully_Second);

			replacedert.IsFalse(gitHubUserService.IsDemoUser);
			replacedert.IsTrue(gitHubUserService.IsAuthenticated);
			replacedert.IsTrue(result);

			void HandleScheduleNotifyTrendingRepositoriesCompleted(object? sender, bool e)
			{
				BackgroundFetchService.ScheduleNotifyTrendingRepositoriesCompleted -= HandleScheduleNotifyTrendingRepositoriesCompleted;
				scheduleNotifyTrendingRepositoriesCompletedTCS.SetResult(e);
			}
		}

19 Source : GitHubAuthenticationServiceTests.cs
with MIT License
from brminnick

[Test]
		public async Task AuthorizeSessionCompletedTest()
		{
			//Arrange
			bool isAuthorizationSuccessful;

			var didAuthorizeSessionCompletedFire = false;
			var authorizeSessionCompletedTCS = new TaskCompletionSource<bool>();

			var gitHubAuthenticationService = ServiceCollection.ServiceProvider.GetRequiredService<GitHubAuthenticationService>();
			GitHubAuthenticationService.AuthorizeSessionCompleted += HandleAuthorizeSessionCompleted;

			//Act
			replacedert.ThrowsAsync<Exception>(async () => await gitHubAuthenticationService.AuthorizeSession(new Uri("https://google.com"), CancellationToken.None).ConfigureAwait(false));
			isAuthorizationSuccessful = await authorizeSessionCompletedTCS.Task.ConfigureAwait(false);

			//replacedert
			replacedert.IsTrue(didAuthorizeSessionCompletedFire);
			replacedert.IsFalse(isAuthorizationSuccessful);


			void HandleAuthorizeSessionCompleted(object? sender, AuthorizeSessionCompletedEventArgs e)
			{
				GitHubAuthenticationService.AuthorizeSessionCompleted -= HandleAuthorizeSessionCompleted;
				didAuthorizeSessionCompletedFire = true;
				authorizeSessionCompletedTCS.SetResult(e.IsSessionAuthorized);
			}
		}

19 Source : GitHubUserServiceTests.cs
with MIT License
from brminnick

[Test]
		public async Task ShouldIncludeOrganizationsTest()
		{
			//Arrange
			bool shouldIncludeOrganizations_Initial, shouldIncludeOrganizations_Final;
			var shouldIncludeOrganizationsChangedTCS = new TaskCompletionSource<bool>();
			var gitHubUserService = ServiceCollection.ServiceProvider.GetRequiredService<GitHubUserService>();

			GitHubUserService.ShouldIncludeOrganizationsChanged += HandleShouldIncludeOrganizationsChanged;

			//Act
			shouldIncludeOrganizations_Initial = gitHubUserService.ShouldIncludeOrganizations;

			gitHubUserService.ShouldIncludeOrganizations = !gitHubUserService.ShouldIncludeOrganizations;
			var shouldIncludeOrganizationsChangedResult = await shouldIncludeOrganizationsChangedTCS.Task.ConfigureAwait(false);

			shouldIncludeOrganizations_Final = gitHubUserService.ShouldIncludeOrganizations;

			//replacedert
			replacedert.IsFalse(shouldIncludeOrganizations_Initial);
			replacedert.IsTrue(shouldIncludeOrganizationsChangedResult);
			replacedert.IsTrue(shouldIncludeOrganizations_Final);

			void HandleShouldIncludeOrganizationsChanged(object? sender, bool e)
			{
				GitHubUserService.ShouldIncludeOrganizationsChanged -= HandleShouldIncludeOrganizationsChanged;
				shouldIncludeOrganizationsChangedTCS.SetResult(e);
			}
		}

19 Source : ReviewServiceTests.cs
with MIT License
from brminnick

[Test]
		public async Task TryRequestReviewPromptTest_Valid()
		{
			//Arrange
			bool didReviewRequestedFire_ReviewService = false;
			bool didReviewRequestedFire_StoreReview = false;

			var reviewRequestedTCS_ReviewService = new TaskCompletionSource<object?>();
			var reviewRequestedTCS_StoreReview = new TaskCompletionSource<bool>();

			MockStoreReview.ReviewRequested += HandleReviewRequested_StoreReview;
			ReviewService.ReviewRequested += HandleReviewRequested_ReviewService;

			var reviewService = ServiceCollection.ServiceProvider.GetRequiredService<ReviewService>();

			var preferences = ServiceCollection.ServiceProvider.GetRequiredService<IPreferences>();
			preferences.Set("AppInstallDate", DateTime.UtcNow.Subtract(TimeSpan.FromDays(ReviewService.MinimumAppInstallDays)));

			//Act
			for (int i = 0; i < ReviewService.MinimumReviewRequests; i++)
			{
				await reviewService.TryRequestReviewPrompt().ConfigureAwait(false);
				replacedert.IsFalse(didReviewRequestedFire_ReviewService);
			}

			await reviewService.TryRequestReviewPrompt().ConfigureAwait(false);
			await reviewRequestedTCS_ReviewService.Task.ConfigureAwait(false);
			var storeReviewResult = await reviewRequestedTCS_StoreReview.Task.ConfigureAwait(false);

			//replacedert
			replacedert.IsTrue(didReviewRequestedFire_ReviewService);
			replacedert.IsTrue(didReviewRequestedFire_StoreReview);
			replacedert.IsTrue(storeReviewResult);
			replacedert.AreNotEqual(preferences.Get("MostRecentRequestDate", default(DateTime)), default);
			replacedert.AreNotEqual(preferences.Get("MostRecentReviewedBuildString", default(string)), default);

			void HandleReviewRequested_ReviewService(object? sender, EventArgs e)
			{
				ReviewService.ReviewRequested -= HandleReviewRequested_ReviewService;

				didReviewRequestedFire_ReviewService = true;
				reviewRequestedTCS_ReviewService.SetResult(null);
			}

			void HandleReviewRequested_StoreReview(object? sender, bool e)
			{
				MockStoreReview.ReviewRequested -= HandleReviewRequested_StoreReview;

				didReviewRequestedFire_StoreReview = true;
				reviewRequestedTCS_StoreReview.SetResult(e);
			}
		}

19 Source : SettingsViewModelTests.cs
with MIT License
from brminnick

[Test]
		public async Task ShouldIncludeOrganizationsSwitchTest()
		{
			//Arrange
			bool isShouldIncludeOrganizationsSwitchEnabled_Initial, isShouldIncludeOrganizationsSwitchEnabled_Final;
			bool isShouldIncludeOrganizationsSwitchToggled_Initial, isShouldIncludeOrganizationsSwitchToggled_Final;

			var organizationsCarouselViewVisibilityChangedTCS = new TaskCompletionSource<bool>();

			var gitHubUserService = ServiceCollection.ServiceProvider.GetRequiredService<GitHubUserService>();
			var settingsViewModel = ServiceCollection.ServiceProvider.GetRequiredService<SettingsViewModel>();
			var gitHubGraphQLApiService = ServiceCollection.ServiceProvider.GetRequiredService<GitHubGraphQLApiService>();
			var azureFunctionsApiService = ServiceCollection.ServiceProvider.GetRequiredService<AzureFunctionsApiService>();
			var gitTrendsStatisticsService = ServiceCollection.ServiceProvider.GetRequiredService<GitTrendsStatisticsService>();

			SettingsViewModel.OrganizationsCarouselViewVisiblilityChanged += HandleOrganizationsCarouselViewVisiblilityChanged;

			//Act
			await gitTrendsStatisticsService.Initialize(CancellationToken.None).ConfigureAwait(false);

			var clientIdDTO = await azureFunctionsApiService.GetGitHubClientId(CancellationToken.None).ConfigureAwait(false);
			var clientId = clientIdDTO.ClientId;

			isShouldIncludeOrganizationsSwitchEnabled_Initial = settingsViewModel.IsShouldIncludeOrganizationsSwitchEnabled;
			isShouldIncludeOrganizationsSwitchToggled_Initial = settingsViewModel.IsShouldIncludeOrganizationsSwitchToggled;

			await AuthenticateUser(gitHubUserService, gitHubGraphQLApiService).ConfigureAwait(false);

			isShouldIncludeOrganizationsSwitchEnabled_Final = settingsViewModel.IsShouldIncludeOrganizationsSwitchEnabled;

			settingsViewModel.IsShouldIncludeOrganizationsSwitchToggled = true;
			var organizationsCarouselViewVisiblilityChangedResult = await organizationsCarouselViewVisibilityChangedTCS.Task.ConfigureAwait(false);

			isShouldIncludeOrganizationsSwitchToggled_Final = settingsViewModel.IsShouldIncludeOrganizationsSwitchToggled;

			//replacedert
			replacedert.IsFalse(isShouldIncludeOrganizationsSwitchEnabled_Initial);
			replacedert.IsFalse(isShouldIncludeOrganizationsSwitchToggled_Initial);

			replacedert.IsTrue(isShouldIncludeOrganizationsSwitchEnabled_Final);
			replacedert.IsTrue(isShouldIncludeOrganizationsSwitchToggled_Final);

			replacedert.IsTrue(organizationsCarouselViewVisiblilityChangedResult);

			void HandleOrganizationsCarouselViewVisiblilityChanged(object? sender, bool e)
			{
				SettingsViewModel.OrganizationsCarouselViewVisiblilityChanged -= HandleOrganizationsCarouselViewVisiblilityChanged;
				organizationsCarouselViewVisibilityChangedTCS.SetResult(e);
			}
		}

19 Source : LockFileHandler.cs
with MIT License
from bryanhitc

private async Task<string> WaitForFileAsync(string path)
        {
            var filePath = Path.Combine(path, FileName);
            if (File.Exists(filePath))
            {
                return filePath;
            }

            var fileCreated = new TaskCompletionSource<bool>();
            var fileWatcher = new FileSystemWatcher(path);

            void OnFileCreated(object sender, FileSystemEventArgs e)
            {
                if (e.Name == FileName)
                {
                    filePath = e.FullPath;
                    fileWatcher.Dispose();
                    fileCreated.SetResult(true);
                }
            }

            fileWatcher.Created += OnFileCreated;
            fileWatcher.EnableRaisingEvents = true;

            await fileCreated.Task.ConfigureAwait(false);
            return filePath;
        }

19 Source : CefNetApi.cs
with MIT License
from CefNet

public static async Task SendAsync(CefThreadId threadId, Action action, CancellationToken cancellationToken)
		{
			if (action == null)
				throw new ArgumentNullException(nameof(action));

			var tcs = new TaskCompletionSource<bool>();
			var internalAction = new Action(() =>
			{
				if (cancellationToken.IsCancellationRequested)
				{
					tcs.SetCanceled();
				}
				else
				{
					try
					{
						action();
					}
					catch (Exception e)
					{
						tcs.SetException(e);
						return;
					}
					tcs.SetResult(true);
				}
			});

			if (!Post(threadId, internalAction))
				throw new InvalidOperationException();

			if (cancellationToken.CanBeCanceled)
			{
				using (var reg = cancellationToken.Register(() => tcs.TrySetCanceled()))
				{
					await tcs.Task.ConfigureAwait(false);
				}
			}
			else
			{
				await tcs.Task.ConfigureAwait(false);
			}
		}

19 Source : CefNetApi.cs
with MIT License
from CefNet

public static async Task SendAsync(CefThreadId threadId, Action action, int delayMs, CancellationToken cancellationToken)
		{
			if (action == null)
				throw new ArgumentNullException(nameof(action));

			var tcs = new TaskCompletionSource<bool>();
			var internalAction = new Action(() =>
			{
				if (cancellationToken.IsCancellationRequested)
				{
					tcs.SetCanceled();
				}
				else
				{
					try
					{
						action();
					}
					catch (Exception e)
					{
						tcs.SetException(e);
						return;
					}
					tcs.SetResult(true);
				}
			});

			if (!Post(threadId, internalAction))
				throw new InvalidOperationException();

			if (cancellationToken.CanBeCanceled)
			{
				using (var reg = cancellationToken.Register(() => tcs.TrySetCanceled()))
				{
					await tcs.Task.ConfigureAwait(false);
				}
			}
			else
			{
				await tcs.Task.ConfigureAwait(false);
			}
		}

19 Source : ProcessExtensions.cs
with GNU General Public License v3.0
from chaincase-app

private static void Process_Exited(object sender, EventArgs e)
		{
			try
			{
				lock (AwaitingTaskCompletionSourcesLock)
				{
					var proc = sender as Process;
					TaskCompletionSource<bool> tcs = AwaitingTaskCompletionSources[proc.Id];
					tcs.SetResult(true);
				}
			}
			catch (Exception ex)
			{
				Logger.LogError(ex, nameof(ProcessExtensions));
			}
		}

19 Source : RCON.cs
with MIT License
from Challengermode

async Task ReadPipeAsync(PipeReader reader)
        {
            byte[] byteArr = new byte[Constants.MAX_PACKET_SIZE];
            while (true)
            {
                ReadResult result = await reader.ReadAsync();
                ReadOnlySequence<byte> buffer = result.Buffer;
                SequencePosition packetStart = buffer.Start;

                if (buffer.Length < 4)
                {
                    if (result.IsCompleted)
                    {
                        break;
                    }
                    reader.AdvanceTo(packetStart, buffer.End);
                    continue;
                    // Complete header not yet received
                }
                int size = BitConverter.ToInt32(buffer.Slice(packetStart, 4).ToArray(), 0);
                if (buffer.Length >= size + 4)
                {
                    // Get packet end positions 
                    SequencePosition packetEnd = buffer.GetPosition(size + 4, packetStart);
                    byteArr = buffer.Slice(packetStart, packetEnd).ToArray();
                    RCONPacket packet = RCONPacket.FromBytes(byteArr);

                    if (packet.Type == PacketType.AuthResponse)
                    {
                        // Failed auth responses return with an ID of -1
                        if (packet.Id == -1)
                        {
                            _authenticationTask.SetException(
                                new AuthenticationException($"Authentication failed for {_tcp.RemoteEndPoint}.")
                                );
                        }
                        // Tell Connect that authentication succeeded
                        _authenticationTask.SetResult(true);
                    }

                    // Forward rcon packet to handler
                    RCONPacketReceived(packet);

                    reader.AdvanceTo(packetEnd);
                }
                else
                {
                    reader.AdvanceTo(packetStart, buffer.End);
                }

                // Tell the PipeReader how much of the buffer we have consumed

                // Stop reading if there's no more data coming
                if (buffer.IsEmpty && result.IsCompleted)
                {
                    break; // exit loop
                }
            }

            // If authentication did not complete
            _authenticationTask.TrySetException(
                                new AuthenticationException($"Server did not respond to auth {_tcp.RemoteEndPoint}.")
                                );

            // Mark the PipeReader as complete
            await reader.CompleteAsync();
        }

19 Source : ShimmerLayout.cs
with Apache License 2.0
from ChasakisD

private async Task StartAnimation()
        {
            CancelAnimation();

            /* First Fade the CanvasView to 1 */
            Device.BeginInvokeOnMainThread(() =>
            {
                _maskCanvasView.Opacity = 0;
                _maskCanvasView.IsVisible = true;
            });

            var widthPixels = Width * _density;
            var gradientSizePixels = GradientSize * Width * 2 * _density;

            var startValue = -gradientSizePixels;
            var endValue = gradientSizePixels + widthPixels;

            var tasks = new[]
            {
                Task.Run(async () => await _maskCanvasView.FadeTo(1, 250U, Easing.Linear)),
                Task.Run(async () =>
                {
                    _animationCancellationTokenSource = new CancellationTokenSource();

                    /* While no cancel requested, continue the loop */
                    while (!_animationCancellationTokenSource.Token.IsCancellationRequested)
                    {
                        _animationCycleCompletionSource = new TaskCompletionSource<bool>();

                        new Animation
                        {
                            {
                                0, 1,
                                new Animation(t => _maskCanvasView.InvalidateSurface("Width", t), startValue, endValue)
                            }
                        }.Commit(_maskCanvasView, ShimmerAnimation, 16, Duration, Easing.Linear,
                            (v, c) => _animationCycleCompletionSource.SetResult(c));

                        /* Wait for the animation completion callback and start it again */
                        await _animationCycleCompletionSource.Task;
                    }
                })
            };

            await Task.WhenAll(tasks);
        }

19 Source : DollyTransition.cs
with GNU General Public License v3.0
from chatrat12

public void Update(float deltaTime)
		{
			if(InProgress)
			{
				var t = _time / _transitionTime;
				UpdateCamera(t);
				_time += deltaTime;
				if (_time >= _transitionTime)
				{
					InProgress = false;
					UpdateCamera(1);
					_transitionTCS?.SetResult(true);
					_transitionTCS = null;
				}
			}
		}

19 Source : SocketClientStub.cs
with MIT License
from ChilliCream

public async ValueTask ReceiveAsync(
            PipeWriter writer,
            CancellationToken cancellationToken = default)
        {
            Increment(x => x.ReceiveAsync(default!, default!));

            LatestCancellationToken = cancellationToken;
            if (MessagesReceive.TryDequeue(out var message))
            {
                var messageAsByte = Encoding.UTF8.GetBytes(message);
                await writer.WriteAsync(new ReadOnlyMemory<byte>(messageAsByte), cancellationToken);
                await writer.FlushAsync(cancellationToken);
                return;
            }

            _completionSource.SetResult(true);

            await Blocker.WaitAsync(cancellationToken);
        }

19 Source : ManagedMqttClient_Tests.cs
with MIT License
from chkr1011

Task GetConnectedTask(ManagedMqttClient managedClient)
        {
            TaskCompletionSource<bool> connected = new TaskCompletionSource<bool>();
            managedClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e =>
            {
                managedClient.ConnectedHandler = null;
                connected.SetResult(true);
            });
            return connected.Task;
        }

19 Source : TcpCommunicator.cs
with MIT License
from Clancey

async Task Run (TaskCompletionSource<bool> tcs)
		{
			try {
				StopListening();
				listener = new TcpListener (IPAddress.Any, serverPort);
				listener.Start ();
			} catch (Exception ex) {
				tcs.SetException (ex);
				return;
			}
			Debug.WriteLine ($"Tcp server listening at port {serverPort}");
			tcs.SetResult (true);

			// Loop
			for (; ; )
			{
				var client = await listener.AcceptTcpClientAsync ();
				var token = new CancellationTokenSource ();
				Receive (client, token.Token);
				var guid = Guid.NewGuid ();
				clients [guid] = new Tuple<TcpClient, CancellationTokenSource> (client, token);

				await Task.Run (async () => {
					await Task.Delay (100);
					await SendToClient (client, GetBytesForObject (new ConnectMessage { ClientId = guid.ToString () }));
				});
				Debug.WriteLine ($"New client connection: {guid}");
				ClientConnected?.Invoke (this, null);
			}
		}

19 Source : StatelessServiceLifecycleTests.cs
with MIT License
from coherentsolutionsinc

private static IStatelessServiceHostDelegateReplicator MockDelegateReplicatorForEvent(
            Action mockDelegate,
            StatelessServiceLifecycleEvent mockEvent)
        {
            var mockDelegateReplicator = new Mock<IStatelessServiceHostDelegateReplicator>();
            mockDelegateReplicator.Setup(instance => instance.ReplicateFor(It.IsAny<IStatelessService>()))
               .Returns(
                    new StatelessServiceDelegate(
                        () =>
                        {
                            var mockTask = new TaskCompletionSource<bool>();
                            var mockDelegateInvoker = new Mock<IStatelessServiceHostDelegateInvoker>();
                            mockDelegateInvoker
                               .Setup(instance => instance.InvokeAsync(It.IsAny<IStatelessServiceDelegateInvocationContext>(), It.IsAny<CancellationToken>()))
                               .Callback(
                                    () =>
                                    {
                                        mockDelegate();
                                        mockTask.SetResult(true);
                                    })
                               .Returns(mockTask.Task);

                            return mockDelegateInvoker.Object;
                        },
                        mockEvent));

            return mockDelegateReplicator.Object;
        }

19 Source : StatefulServiceLifecycleTests.cs
with MIT License
from coherentsolutionsinc

private static IStatefulServiceHostDelegateReplicator MockDelegateReplicatorForEvent(
            Action mockDelegate,
            StatefulServiceLifecycleEvent mockEvent)
        {
            var mockDelegateReplicator = new Mock<IStatefulServiceHostDelegateReplicator>();
            mockDelegateReplicator.Setup(instance => instance.ReplicateFor(It.IsAny<IStatefulService>()))
               .Returns(
                    new StatefulServiceDelegate(
                        () =>
                        {
                            var mockTask = new TaskCompletionSource<bool>();
                            var mockDelegateInvoker = new Mock<IStatefulServiceHostDelegateInvoker>();
                            mockDelegateInvoker.Setup(
                                    instance => instance.InvokeAsync(It.IsAny<IStatefulServiceDelegateInvocationContext>(), It.IsAny<CancellationToken>()))
                               .Callback(
                                    () =>
                                    {
                                        mockDelegate();
                                        mockTask.SetResult(true);
                                    })
                               .Returns(mockTask.Task);

                            return mockDelegateInvoker.Object;
                        },
                        mockEvent));

            return mockDelegateReplicator.Object;
        }

19 Source : NotifyAsyncEventArgsExtensions.cs
with MIT License
from coherentsolutionsinc

private static Task InvokeAsync(
            Delegate @delegate,
            Action<(Delegate method, object sender, CancellationToken cancellationToken, Action completion, Action<Exception> failure)> invocation,
            object source,
            CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource<bool>();
            var methods = @delegate.GetInvocationList();

            var remaining = methods.Length;

            Exception invocationException = null;
            foreach (var method in methods)
            {
                var sync = new object();

                var invoked = false;

                var complete = new Action(
                    () =>
                    {
                        if (invoked)
                        {
                            return;
                        }

                        lock (sync)
                        {
                            if (invoked)
                            {
                                return;
                            }

                            invoked = true;
                        }

                        if (Interlocked.Decrement(ref remaining) == 0)
                        {
                            switch (invocationException)
                            {
                                case null:
                                    tcs.SetResult(true);
                                    break;
                                case OperationCanceledException _:
                                    tcs.SetCanceled();
                                    break;
                                default:
                                    tcs.SetException(invocationException);
                                    break;
                            }
                        }
                    });
                var fail = new Action<Exception>(
                    exception =>
                    {
                        if (invoked)
                        {
                            return;
                        }

                        lock (sync)
                        {
                            if (invoked)
                            {
                                return;
                            }

                            invocationException = exception;
                            invoked = true;
                        }

                        if (Interlocked.Decrement(ref remaining) != 0)
                        {
                            return;
                        }

                        if (exception is OperationCanceledException)
                        {
                            tcs.SetCanceled();
                        }
                        else
                        {
                            tcs.SetException(exception);
                        }
                    });

                try
                {
                    invocation((method, source, cancellationToken, complete, failure: fail));
                }
                catch (TargetInvocationException e) when (e.InnerException != null)
                {
                    fail(e.InnerException);
                }
                catch (Exception e)
                {
                    fail(e);
                }
            }

            return tcs.Task;
        }

19 Source : FaceClient.cs
with MIT License
from colbylwilliams

void NoopResultCallback (NSError error, TaskCompletionSource<bool> tcs)
		{
			try
			{
				ProcessError (error);
				tcs.SetResult (true);
			}
			catch (Exception ex)
			{
				Log.Error (ex);
				tcs.TrySetException (ex);
			}
		}

19 Source : PeerConnectorTests.cs
with MIT License
from comrade-coop

[Theory]
#endif
        [MemberData(nameof(SamplePubSubData))]
        public async void PubSub_AfterListenPubSub_SendsPubSub(string connectorImplementation, IExample dataMessage)
        {
            var connectorTo = _fixture.GetPeerConnector(connectorImplementation, 1);
            var connectorFrom = _fixture.GetPeerConnector(connectorImplementation, 2);

            var cancellationTokenSource = new CancellationTokenSource(TestData.WaitTime * 3); // Prevent hangs

            var path = $"test-{Guid.NewGuid()}";

            var receiveTasks = new List<Task>();
            foreach (var connector in new[] { connectorTo, connectorFrom })
            {
                var received = new TaskCompletionSource<bool>();
                receiveTasks.Add(received.Task);
                cancellationTokenSource.Token.Register(() => received.TrySetCanceled());

                await connector.ListenPubSub<IExample>(path, async (otherPeer, message) =>
                {
                    if (message == null) return false;
                    replacedert.Equal(otherPeer, await connectorFrom.Self);
                    replacedert.Equal(message, dataMessage, SerializedComparer.Instance);
                    received.SetResult(true);
                    return true;
                }, cancellationTokenSource.Token);
                await connectorFrom.SendPubSub<IExample?>(path, null);
            };

            await Task.Delay(TestData.WaitTime);

            await connectorFrom.SendPubSub<IExample>(path, dataMessage, cancellationTokenSource.Token);

            await Task.WhenAll(receiveTasks);

            cancellationTokenSource.Cancel();
        }

19 Source : SemaphoreSlimmer.cs
with MIT License
from connellw

public void Release()
        {
            lock (_lock)
            {
                if (_currentCount == 0)
                    throw new Exception("No task waiting on this semapreplaced to release.");

                _currentCount--;

                if (_currentCount > 0)
                    return;

                if (_tcs != null)
                {
                    _tcs.SetResult(true);
                    _tcs = null;
                }
            }
        }

19 Source : Dispatcher.cs
with MIT License
from Const-me

static void yieldImpl( object obj )
		{
			TaskCompletionSource<bool> tcs = (TaskCompletionSource<bool>)obj;
			tcs.SetResult( true );
		}

19 Source : Dispatcher.cs
with MIT License
from Const-me

public Task post( Action action )
		{
			TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
			Action actPost = () =>
			{
				try
				{
					action();
					tcs.SetResult( true );
				}
				catch( Exception ex )
				{
					tcs.SetException( ex );
				}
			};
			postAction( actPost );
			return tcs.Task;
		}

19 Source : Dispatcher.cs
with MIT License
from Const-me

public Task postTask( Func<Task> asyncTask )
		{
			TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
			Action actPost = async () =>
			{
				try
				{
					Task task = asyncTask();
					await task;
					tcs.SetResult( true );
				}
				catch( Exception ex )
				{
					tcs.SetException( ex );
				}
			};
			postAction( actPost );
			return tcs.Task;
		}

19 Source : MediaEngineExt.cs
with MIT License
from Const-me

void iCompletionSource.completed() => tcs.SetResult( true );

19 Source : LinuxEngine.cs
with MIT License
from Const-me

void loadMediaImpl( string url, TaskCompletionSource<bool> completionSource )
		{
			try
			{
				// Deal with paths starting from "~/", transform that into user's home folder
				if( url.StartsWith( "~/" ) )
				{
					string rel = url.Substring( 2 );
					string home = Environment.GetFolderPath( Environment.SpecialFolder.UserProfile );
					url = Path.Combine( home, rel );
				}

				// Parse the complete MP4, except the largest `mdat` box which has the actual payload of the video.
				file = OpenMedia.openMedia( File.OpenRead( url ) );

				if( !shutdownHandle )
					shutdownHandle = EventHandle.create();

				// Initialize the video
				if( null == file.videoTrack )
					throw new ApplicationException( "The file doesn’t have a video track" );
				decoder?.Dispose();
				decoder = new StatefulVideoDecoder( h264.device, shutdownHandle );

				int videoEncodedBuffers = encodedBuffersCount;
				int audioEncodedBuffers = this.audioEncodedBuffers;

				decoder.initialize( file.videoTrack, videoEncodedBuffers );
				decodedSize = file.videoTrack.decodedSize;
				decoder.captureSetup( file.videoTrack, decodedBuffersCount, decodedSize );

				// Initialize the audio
				audioPlayer?.Dispose();
				audioPlayer = null;
				if( null != file.audioTrack )
				{
					try
					{
						audioPlayer = Audio.Player.create( file.audioTrack, audioEncodedBuffers, shutdownHandle );
					}
					catch( Exception ex )
					{
						// Logger.logError( ex.ToString() );
						ex.logError( "Error initializing audio" );
					}
				}
				else
					Logger.logWarning( "The file doesn’t have an audio track" );

				// Initialize presentation clock source
				if( null != audioPlayer )
				{
					// Use audio player for the source of presentation time
					if( displayRefresh.HasValue )
						presentationClock = new Clocks.AudioWithTimer( decoder, audioPlayer, displayRefresh.Value );
					else
						presentationClock = new Clocks.Audio( decoder, audioPlayer );
				}
				else
				{
					// Use eClock.Monotonic OS clock for presentation time
					presentationClock = new Clocks.Video( decoder );
				}
				m_state = eState.Prepared;
				if( m_autoPlay )
					play();

				completionSource.SetResult( true );
			}
			catch( Exception ex )
			{
				completionSource.SetException( ex );
			}
		}

19 Source : MonoCamera.cs
with MIT License
from cookieofcode

private void OnStoppedPhotoMode(PhotoCapture.PhotoCaptureResult result)
        {
            _photoCaptureObject?.Dispose();
            _photoCaptureObject = null;
            _stopped.SetResult(true);
            Debug.Log("Photo mode stopped.");
        }

19 Source : Utils.cs
with Apache License 2.0
from cosmos-loops

public static Task PostContinueWith<T>(this Task<T> task, Action<Task<T>> action) {
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();

            task.ContinueWith
            (
                task2 => {
                    ThreadPool.QueueUserWorkItem
                    (
                        obj => {
                            try {
                                action(task2);
                                tcs.SetResult(true);
                            } catch (Exception exc) {
                                tcs.SetException(exc);
                            }
                        }
                    );
                },
                TaskContinuationOptions.None
            );

            return tcs.Task;
        }

19 Source : Hosting.cs
with BSD 2-Clause "Simplified" License
from countincognito

private static void RunHost()
        {
            MagicOnionServiceDefinition service = MagicOnionEngine.BuildServerServiceDefinition(
                new[] { typeof(UserAccessGrpc) },
                new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true));

            // SSL gRPC
            string caCrt = File.ReadAllText(EnvVars.CaCrtPath());
            string serverCrt = File.ReadAllText(EnvVars.ServerCrtPath());
            string serverKey = File.ReadAllText(EnvVars.ServerKeyPath());
            var keyPair = new KeyCertificatePair(serverCrt, serverKey);
            var sslCredentials = new SslServerCredentials(new List<KeyCertificatePair>() { keyPair }, caCrt, false);

            int localPort = EnvVars.LocalPort(@"UserAccessPort");

            var server = new global::Grpc.Core.Server
            {
                Services = { service },
                Ports = { new ServerPort("0.0.0.0", localPort, sslCredentials) }
            };

            // launch gRPC Server.
            server.Start();

            Log.Information($"Server listening on port {localPort}");

            var cts = new CancellationTokenSource();

            var syncTask = new TaskCompletionSource<bool>();

            System.Runtime.Loader.replacedemblyLoadContext.Default.Unloading += (context) =>
            {
                Log.Information("Greeter server received kill signal...");
                cts.Cancel();
                server.ShutdownAsync().Wait();
                syncTask.SetResult(true);
            };
            syncTask.Task.Wait(-1);
            Log.Information("Greeter server stopped");
        }

19 Source : Hosting.cs
with BSD 2-Clause "Simplified" License
from countincognito

private static void RunHost()
        {
            MagicOnionServiceDefinition service = MagicOnionEngine.BuildServerServiceDefinition(
                new[] { typeof(MembershipManagerGrpc) },
                new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true));

            // SSL gRPC
            string caCrt = File.ReadAllText(EnvVars.CaCrtPath());
            string serverCrt = File.ReadAllText(EnvVars.ServerCrtPath());
            string serverKey = File.ReadAllText(EnvVars.ServerKeyPath());
            var keyPair = new KeyCertificatePair(serverCrt, serverKey);
            var sslCredentials = new SslServerCredentials(new List<KeyCertificatePair>() { keyPair }, caCrt, false);

            int localPort = EnvVars.LocalPort(@"MembershipManagerPort");

            var server = new global::Grpc.Core.Server
            {
                Services = { service },
                Ports = { new ServerPort("0.0.0.0", localPort, sslCredentials) }
            };

            // launch gRPC Server.
            server.Start();

            Log.Information($"Server listening on port {localPort}");

            var cts = new CancellationTokenSource();

            var syncTask = new TaskCompletionSource<bool>();

            System.Runtime.Loader.replacedemblyLoadContext.Default.Unloading += (context) =>
            {
                Log.Information("Greeter server received kill signal...");
                cts.Cancel();
                server.ShutdownAsync().Wait();
                syncTask.SetResult(true);
            };
            syncTask.Task.Wait(-1);
            Log.Information("Greeter server stopped");
        }

19 Source : Hosting.cs
with BSD 2-Clause "Simplified" License
from countincognito

private static void RunHost()
        {
            MagicOnionServiceDefinition service = MagicOnionEngine.BuildServerServiceDefinition(
                new[] { typeof(RegistrationEngineGrpc) },
                new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true));

            // SSL gRPC
            string caCrt = File.ReadAllText(EnvVars.CaCrtPath());
            string serverCrt = File.ReadAllText(EnvVars.ServerCrtPath());
            string serverKey = File.ReadAllText(EnvVars.ServerKeyPath());
            var keyPair = new KeyCertificatePair(serverCrt, serverKey);
            var sslCredentials = new SslServerCredentials(new List<KeyCertificatePair>() { keyPair }, caCrt, false);

            int localPort = EnvVars.LocalPort(@"RegistrationEnginePort");

            var server = new global::Grpc.Core.Server
            {
                Services = { service },
                Ports = { new ServerPort("0.0.0.0", localPort, sslCredentials) }
            };

            // launch gRPC Server.
            server.Start();

            Log.Information($"Server listening on port {localPort}");

            var cts = new CancellationTokenSource();

            var syncTask = new TaskCompletionSource<bool>();

            System.Runtime.Loader.replacedemblyLoadContext.Default.Unloading += (context) =>
            {
                Log.Information("Greeter server received kill signal...");
                cts.Cancel();
                server.ShutdownAsync().Wait();
                syncTask.SetResult(true);
            };
            syncTask.Task.Wait(-1);
            Log.Information("Greeter server stopped");
        }

19 Source : AsyncLock.cs
with Apache License 2.0
from crazyants

public void Release()
        {
            TaskCompletionSource<bool> toRelease = null;
            lock (m_waiters)
            {
                if (m_waiters.Count > 0)
                    toRelease = m_waiters.Dequeue();
                else
                    ++m_currentCount;
            }
            if (toRelease != null)
                toRelease.SetResult(true);
        }

19 Source : Require.cs
with MIT License
from curiosity-ai

public static async Task LoadScriptAsync(params string[] libraries)
        {
            await singleCall.WaitAsync();

            var tcs = new TaskCompletionSource<bool>();
            LoadScriptAsync(() => tcs.SetResult(true), (err) => tcs.SetException(new Exception(err)), libraries);
            await tcs.Task;

            singleCall.Release();
        }

See More Examples