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

Here are the examples of the csharp api System.Threading.Tasks.TaskCompletionSource.SetResult(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

176 Examples 7

19 Source : Program.cs
with MIT License
from andreaschiavinato

static void Main(string[] args)
    {
        var client = new JupyterBlockingClient();

        //Getting available kernels
        var kernels = client.GetKernels();
        if (kernels.Count == 0)
            throw new Exception("No kernels found");

        //Connecting to the first kernel found
        Console.WriteLine($"Connecting to kernel {kernels.First().Value.spec.display_name}");
        client.StartKernel(kernels.First().Key);
        Console.WriteLine("Connected\n");

        //Loading a script containing the definition of the function do_something
        client.Execute("%run script.py");

        //Creating an event handler that stores the result of the computation in a TaskCompletionSource object 
        var promise = new TaskCompletionSource<string>();
        EventHandler<JupyterMessage> hanlder = (sender, message) =>
        {
            if (message.header.msg_type == JupyterMessage.Header.MsgType.execute_result)
            {
                var content = (JupyterMessage.ExecuteResultContent)message.content;
                promise.SetResult(content.data[MimeTypes.TextPlain]);
            }
            else if (message.header.msg_type == JupyterMessage.Header.MsgType.error)
            {
                var content = (JupyterMessage.ErrorContent)message.content;
                promise.SetException(new Exception($"Jupyter kenel error: {content.ename} {content.evalue}"));
            }
        };
        client.OnOutputMessage += hanlder;
        //calling the function do_something
        client.Execute("do_something(2)");
        //removing event handler, since the TaskCompletionSource cannot be reused
        client.OnOutputMessage -= hanlder;

        //getting the result
        try
        {
            Console.WriteLine("Result:");
            if (promise.Task.IsCompleted)
                Console.WriteLine(promise.Task.Result);
            else
                Console.WriteLine("No result received");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        finally
        {
            //Closing the kernel
            client.Shutdown();
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
    }

19 Source : AccessTokenManager.cs
with MIT License
from ansel86castro

public async ValueTask<string> GetToken()
        {
            if (token == null)
            {
                if (Interlocked.CompareExchange(ref _authenticate, 1, 0) == 0)
                {
                    _tcs = new TaskCompletionSource<string>();
                    try
                    {
                        token = await _client.GetClientCredentialsTokenAsync(_options.ClientId, _options.ClientSecret, _options.Scope);
                        _tcs.SetResult(token);
                    }
                    catch (Exception e)
                    {
                        _tcs.SetException(e);

                        if (e is AggregateException ag && ag.InnerExceptions.Count == 1)
                            throw e.InnerException;

                        throw;
                    }
                }
                else
                {
                    while (_tcs == null) { Thread.SpinWait(5); }

                    await _tcs.Task;
                }

            }

            return token;
        }

19 Source : RabbitMessageBusTests.cs
with MIT License
from ArmandJ77

[Test]
        public async Task Given_Subscribe_TestMessageTopic_Expect_HelloWorld_Response()
        {
            const string topic = "TestMessageTopic";
            const string subscriptionId = "SubscribeToTestMessage";
            const string message = "Hello World";
            var result = await MessageBrokerClient.Publish<string>(topic, message);

            var subscriptionResponse = await MessageBrokerClient.Subscribe<string>(topic,
                subscriptionId, replacedertCallback, c => c.UseBasicQos());

            static Task replacedertCallback(string messageEvent)
            {
                var tcs = new TaskCompletionSource<string>();
                Stringreplacedert.AreEqualIgnoringCase("HelloWorld", messageEvent);
                tcs.SetResult(messageEvent);
                return tcs.Task;
            }
        }

19 Source : ServiceHubContextE2EFacts.cs
with MIT License
from Azure

[ConditionalTheory]
        [SkipIfConnectionStringNotPresent]
        [MemberData(nameof(TestData))]
        public async Task CloseConnectionTest(ServiceTransportType serviceTransportType, string appName)
        {
            //when ServiceHubContext.Dispose in persistent mode, there is always an error, so we can not use VerifiableLog
            using (StartLog(out var loggerFactory))
            {
                ServiceHubContext serviceHubContext = null;
                try
                {
                    const string reason = "This is a test reason.";
                    var serviceManager = new ServiceManagerBuilder()
                        .WithOptions(o =>
                        {
                            o.ConnectionString = TestConfiguration.Instance.ConnectionString;
                            o.ServiceTransportType = serviceTransportType;
                            o.ApplicationName = appName;
                        })
                        .WithLoggerFactory(loggerFactory)
                        .Build();
                    serviceHubContext = (await serviceManager.CreateHubContextAsync(HubName)) as ServiceHubContext;
                    var negotiationRes = await serviceHubContext.NegotiateAsync(new NegotiationOptions { EnableDetailedErrors = true, IsDiagnosticClient = true });
                    var conn = CreateHubConnection(negotiationRes.Url, negotiationRes.AccessToken);
                    var tcs = new TaskCompletionSource<string>();
                    conn.Closed += ex =>
                    {
                        if (ex is null)
                        {
                            tcs.SetException(new Exception("close exception is null"));
                        }
                        tcs.SetResult(ex.Message);
                        return Task.CompletedTask;
                    };
                    await conn.StartAsync();
                    await serviceHubContext.ClientManager.CloseConnectionAsync(conn.ConnectionId, reason);

                    var actualReason = await tcs.Task.OrTimeout();
                    replacedert.Contains(reason, actualReason);
                }
                finally
                {
                    await serviceHubContext?.DisposeAsync();
                }
            }
        }

19 Source : ClipboardService.cs
with MIT License
from Basaingeal

[JSInvokable]
        public static void ReceiveReadResponse(string id, string text)
        {
            TaskCompletionSource<string> pendingTask;
            var idVal = Guid.Parse(id);
            pendingTask = pendingReadRequests.First(x => x.Key == idVal).Value;
            pendingTask.SetResult(text);
            pendingReadRequests.Remove(idVal);
        }

19 Source : MaterialInputDialog.xaml.cs
with MIT License
from Baseflow

protected override void OnBackButtonDismissed()
        {
            InputTaskCompletionSource?.SetResult(string.Empty);
        }

19 Source : MaterialInputDialog.xaml.cs
with MIT License
from Baseflow

protected override bool OnBackgroundClicked()
        {
            InputTaskCompletionSource?.SetResult(string.Empty);

            return base.OnBackgroundClicked();
        }

19 Source : EmojiPicker.cs
with MIT License
from bezysoftware

public static async Task<string> ShowAsync()
        {
            var picker = new EmojiPicker();
            var container = new Grid
            {
                Width = Window.Current.Bounds.Width,
                Height = Window.Current.Bounds.Height,
                Background = new SolidColorBrush(new Color { A = 100, R = 100, G = 100, B = 100 })
            };
            container.Children.Add(picker);

            openPopup = new Popup
            {
                IsLightDismissEnabled = true,
                LightDismissOverlayMode = LightDismissOverlayMode.On,
                Child = container,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,
                ChildTransitions = new TransitionCollection
                {
                    new ContentThemeTransition()
                },
                IsOpen = true
            };

            picker.Focus(FocusState.Programmatic);

            var tcs = new TaskCompletionSource<string>();

            openPopup.Closed += (_, __) => tcs.SetResult(picker.selectedEmoji);

            return await tcs.Task;
        }

19 Source : BaseViewModel.cs
with MIT License
from Binwell

protected static Task<string> ShowSheet(string replacedle, string cancel, string destruction, string[] items) {
			var tcs = new TaskCompletionSource<string>();
			MessageBus.SendMessage(Consts.DialogSheetMessage,
				new DialogSheetInfo {
					replacedle = replacedle,
					Cancel = cancel,
					Destruction = destruction,
					Items = items,
					OnCompleted = s => tcs.SetResult(s)
				});
			return tcs.Task;
		}

19 Source : BaseViewModel.cs
with MIT License
from Binwell

protected static Task<string> ShowEntryAlert(string replacedle, string message, string cancel, string ok, string placeholder) {
			var tcs = new TaskCompletionSource<string>();
			MessageBus.SendMessage(Consts.DialogEntryMessage,
				new DialogEntryInfo {
					replacedle = replacedle,
					Message = message,
					Cancel = cancel,
					Ok = ok,
					Placeholder = placeholder,
					OnCompleted = s => tcs.SetResult(s),
					OnCancelled = () => tcs.SetResult(null)
				});
			return tcs.Task;
		}

19 Source : BaseViewModel.cs
with MIT License
from Binwell

protected static Task<string> ShowEntryAlert(string replacedle, string message, string cancel, string ok, string placeholder) {
			var tcs = new TaskCompletionSource<string>();
			MessageBus.SendMessage(Consts.DialogEntryMessage,
				new DialogEntryInfo {
					replacedle = replacedle,
					Message = message,
					Cancel = cancel,
					Ok = ok,
					Placeholder = placeholder,
					OnCompleted = s => tcs.SetResult(s),
					OnCancelled = () => tcs.SetResult(null)
				});
			return tcs.Task;
		}

19 Source : Basic.cs
with MIT License
from bording

void Handle_ConsumeOk(object tcs, ReadOnlySequence<byte> arguments, Exception exception)
        {
            var consumeOk = (TaskCompletionSource<string>)tcs;

            if (exception != null)
            {
                consumeOk.SetException(exception);
            }
            else
            {
                var reader = new CustomBufferReader(arguments);

                var consumerTag = reader.ReadShortString();

                consumers.Add(consumerTag, pendingConsumer);

                consumeOk.SetResult(consumerTag);
            }

            pendingConsumer = null;
        }

19 Source : Basic.cs
with MIT License
from bording

void Handle_CancelOk(object tcs, ReadOnlySequence<byte> arguments, Exception exception)
        {
            var cancelOk = (TaskCompletionSource<string>)tcs;

            if (exception != null)
            {
                cancelOk.SetException(exception);
            }
            else
            {
                var reader = new CustomBufferReader(arguments);
                var consumerTag = reader.ReadShortString();
                cancelOk.SetResult(consumerTag);
            }
        }

19 Source : NuGetService.cs
with MIT License
from brminnick

async IAsyncEnumerable<string> GetCsprojFiles([EnumeratorCancellation] CancellationToken cancellationToken)
		{
			var getCSProjFileTaskList = new List<(string csprojFilePath, TaskCompletionSource<string> csprojSourceCodeTCS)>();
			foreach (var csprojFilePath in _csProjFilePaths)
			{
				getCSProjFileTaskList.Add((csprojFilePath, new TaskCompletionSource<string>()));
			}

			Parallel.ForEach(getCSProjFileTaskList, async getCSProjFileTask =>
			{
				var repositoryFile = await _gitHubApiV3Service.GetGitTrendsFile(getCSProjFileTask.csprojFilePath, cancellationToken).ConfigureAwait(false);
				var file = await _client.GetStringAsync(repositoryFile.DownloadUrl).ConfigureAwait(false);

				getCSProjFileTask.csprojSourceCodeTCS.SetResult(file);
			});

			var remainingTasks = getCSProjFileTaskList.Select(x => x.csprojSourceCodeTCS.Task).ToList();

			while (remainingTasks.Any())
			{
				var completedTask = await Task.WhenAny(remainingTasks).ConfigureAwait(false);
				remainingTasks.Remove(completedTask);

				var csprojFile = await completedTask.ConfigureAwait(false);
				yield return csprojFile;
			}
		}

19 Source : BackgroundFetchServiceTests.cs
with MIT License
from brminnick

[Test]
		public async Task ScheduleRetryOrganizationsRepositoriesTest_AuthenticatedUser()
		{
			//Arrange
			bool wreplacedcheduledSuccessfully_First, wreplacedcheduledSuccessfully_Second;
			string organizationName_Initial = nameof(GitTrends), organizationName_Final;
			Repository repository_Final, repository_Database;

			var scheduleRetryOrganizationsRepositoriesCompletedTCS = new TaskCompletionSource<string>();
			var scheduleRetryRepositoriesViewsClonesCompletedTCS = new TaskCompletionSource<Repository>();
			BackgroundFetchService.ScheduleRetryRepositoriesViewsClonesCompleted += HandleScheduleRetryRepositoriesViewsClonesCompleted;
			BackgroundFetchService.ScheduleRetryOrganizationsRepositoriesCompleted += HandleScheduleRetryOrganizationsRepositoriesCompleted;

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

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

			//Act
			wreplacedcheduledSuccessfully_First = backgroundFetchService.TryScheduleRetryOrganizationsRepositories(organizationName_Initial);
			wreplacedcheduledSuccessfully_Second = backgroundFetchService.TryScheduleRetryOrganizationsRepositories(organizationName_Initial);

			organizationName_Final = await scheduleRetryOrganizationsRepositoriesCompletedTCS.Task.ConfigureAwait(false);

			repository_Final = await scheduleRetryRepositoriesViewsClonesCompletedTCS.Task.ConfigureAwait(false);
			repository_Database = await repositoryDatabase.GetRepository(repository_Final.Url).ConfigureAwait(false) ?? throw new NullReferenceException();

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

			replacedert.AreEqual(organizationName_Initial, organizationName_Final);

			replacedert.IsTrue(repository_Final.ContainsTrafficData);
			replacedert.IsTrue(repository_Database.ContainsTrafficData);

			replacedert.IsNotNull(repository_Final.DailyClonesList);
			replacedert.IsNotNull(repository_Final.DailyViewsList);
			replacedert.IsNotNull(repository_Final.StarredAt);
			replacedert.IsNotNull(repository_Final.TotalClones);
			replacedert.IsNotNull(repository_Final.TotalUniqueClones);
			replacedert.IsNotNull(repository_Final.TotalUniqueViews);
			replacedert.IsNotNull(repository_Final.TotalViews);

			replacedert.IsNotNull(repository_Database.DailyClonesList);
			replacedert.IsNotNull(repository_Database.DailyViewsList);
			replacedert.IsNotNull(repository_Database.StarredAt);
			replacedert.IsNotNull(repository_Database.TotalClones);
			replacedert.IsNotNull(repository_Database.TotalUniqueClones);
			replacedert.IsNotNull(repository_Database.TotalUniqueViews);
			replacedert.IsNotNull(repository_Database.TotalViews);

			replacedert.AreEqual(repository_Final.Name, repository_Database.Name);
			replacedert.AreEqual(repository_Final.Description, repository_Database.Description);
			replacedert.AreEqual(repository_Final.ForkCount, repository_Database.ForkCount);
			replacedert.AreEqual(repository_Final.IsFavorite, repository_Database.IsFavorite);
			replacedert.AreEqual(repository_Final.IsFork, repository_Database.IsFork);
			replacedert.AreEqual(repository_Final.IssuesCount, repository_Database.IssuesCount);
			replacedert.AreEqual(repository_Final.IsTrending, repository_Database.IsTrending);

			void HandleScheduleRetryRepositoriesViewsClonesCompleted(object? sender, Repository e)
			{
				BackgroundFetchService.ScheduleRetryRepositoriesViewsClonesCompleted -= HandleScheduleRetryRepositoriesViewsClonesCompleted;
				scheduleRetryRepositoriesViewsClonesCompletedTCS.SetResult(e);
			}

			void HandleScheduleRetryOrganizationsRepositoriesCompleted(object? sender, string e)
			{
				BackgroundFetchService.ScheduleRetryOrganizationsRepositoriesCompleted -= HandleScheduleRetryOrganizationsRepositoriesCompleted;
				scheduleRetryOrganizationsRepositoriesCompletedTCS.SetResult(e);
			}
		}

19 Source : GitHubUserServiceTests.cs
with MIT License
from brminnick

[Test]
		public async Task AliasTest()
		{
			//Arrange
			string alias_Initial, aliasChangedResult, alias_Final;

			bool didAliasChangedFire = false;
			var aliasChangedTCS = new TaskCompletionSource<string>();

			GitHubUserService.AliasChanged += HandleAliasChanged;

			var gitHubUserService = ServiceCollection.ServiceProvider.GetRequiredService<GitHubUserService>();
			alias_Initial = gitHubUserService.Alias;

			//Act
			gitHubUserService.Alias = GitHubConstants.GitTrendsRepoOwner;
			aliasChangedResult = await aliasChangedTCS.Task.ConfigureAwait(false);
			alias_Final = gitHubUserService.Alias;

			//replacedert
			replacedert.IsTrue(didAliasChangedFire);
			replacedert.AreEqual(string.Empty, alias_Initial);
			replacedert.AreEqual(GitHubConstants.GitTrendsRepoOwner, alias_Final);
			replacedert.AreEqual(alias_Final, aliasChangedResult);


			void HandleAliasChanged(object? sender, string e)
			{
				GitHubUserService.AliasChanged -= HandleAliasChanged;

				didAliasChangedFire = true;
				aliasChangedTCS.SetResult(e);
			}
		}

19 Source : GitHubUserServiceTests.cs
with MIT License
from brminnick

[Test]
		public async Task NameTest()
		{
			//Arrange
			const string expectedName = "Brandon Minnick";

			string name_Initial, nameChangedResult, name_Final;

			bool didNameChangedFire = false;
			var nameChangedTCS = new TaskCompletionSource<string>();

			GitHubUserService.NameChanged += HandleNameChanged;

			var gitHubUserService = ServiceCollection.ServiceProvider.GetRequiredService<GitHubUserService>();
			name_Initial = gitHubUserService.Name;

			//Act
			gitHubUserService.Name = expectedName;
			nameChangedResult = await nameChangedTCS.Task.ConfigureAwait(false);
			name_Final = gitHubUserService.Name;

			//replacedert
			replacedert.IsTrue(didNameChangedFire);
			replacedert.AreEqual(string.Empty, name_Initial);
			replacedert.AreEqual(expectedName, name_Final);
			replacedert.AreEqual(name_Final, nameChangedResult);


			void HandleNameChanged(object? sender, string e)
			{
				GitHubUserService.NameChanged -= HandleNameChanged;

				didNameChangedFire = true;
				nameChangedTCS.SetResult(e);
			}
		}

19 Source : GitHubUserServiceTests.cs
with MIT License
from brminnick

[Test]
		public async Task AvatarUrlTest()
		{
			//Arrange
			string avatarUrl_Initial, avatarUrlChangedResult, avatarUrl_Final;

			bool didAvatarUrlChangedFire = false;
			var avatarUrlChangedTCS = new TaskCompletionSource<string>();

			GitHubUserService.AvatarUrlChanged += HandleAvatarUrlChanged;

			var gitHubUserService = ServiceCollection.ServiceProvider.GetRequiredService<GitHubUserService>();
			avatarUrl_Initial = gitHubUserService.AvatarUrl;

			//Act
			gitHubUserService.AvatarUrl = AuthenticatedGitHubUserAvatarUrl;
			avatarUrlChangedResult = await avatarUrlChangedTCS.Task.ConfigureAwait(false);
			avatarUrl_Final = gitHubUserService.AvatarUrl;

			//replacedert
			replacedert.IsTrue(didAvatarUrlChangedFire);
			replacedert.AreEqual(string.Empty, avatarUrl_Initial);
			replacedert.AreEqual(AuthenticatedGitHubUserAvatarUrl, avatarUrl_Final);
			replacedert.AreEqual(avatarUrl_Final, avatarUrlChangedResult);


			void HandleAvatarUrlChanged(object? sender, string e)
			{
				GitHubUserService.AvatarUrlChanged -= HandleAvatarUrlChanged;

				didAvatarUrlChangedFire = true;
				avatarUrlChangedTCS.SetResult(e);
			}
		}

19 Source : LanguageServiceTests.cs
with MIT License
from brminnick

[Test]
		public async Task ConfirmLanguageChanges_SetPreferedLanguage()
		{
			//Arrange
			CultureInfo? currentCulture_Initial, currentUICulture_Initial, currentCulture_Final, currentUICulture_Final;

			//Don't execute null or string.Empty first to ensure PreferredLanguageChanged fires (default value of LanguageService.PerferredLanguage is null)
			var availableLanguages = new List<string?>();
			availableLanguages.AddRange(CultureConstants.CulturePickerOptions.Keys.Reverse().ToList());
			availableLanguages.Insert(1, null);

			var languageService = ServiceCollection.ServiceProvider.GetRequiredService<LanguageService>();

			foreach (var language in availableLanguages)
			{
				bool didPreferredLanguageChangeFire = false;
				var preferredLanguageChangedTCS = new TaskCompletionSource<string?>();

				LanguageService.PreferredLanguageChanged += HandlePreferredLanguageChanged;

				//Act
				currentCulture_Initial = CultureInfo.DefaultThreadCurrentCulture;
				currentUICulture_Initial = CultureInfo.DefaultThreadCurrentUICulture;

				languageService.PreferredLanguage = language;
				var preferredLanguageChangedResult = await preferredLanguageChangedTCS.Task.ConfigureAwait(false);

				currentCulture_Final = CultureInfo.DefaultThreadCurrentCulture;
				currentUICulture_Final = CultureInfo.DefaultThreadCurrentUICulture;

				//replacedert
				replacedert.IsTrue(didPreferredLanguageChangeFire);

				if (string.IsNullOrWhiteSpace(language))
				{
					replacedert.IsNull(currentCulture_Final);
					replacedert.IsNull(currentUICulture_Final);
				}
				else
				{
					replacedert.IsNotNull(currentCulture_Final);
					replacedert.IsNotNull(currentUICulture_Final);
				}

				replacedert.AreNotEqual(currentCulture_Final, currentCulture_Initial);
				replacedert.AreNotEqual(currentUICulture_Final, currentUICulture_Initial);

				replacedert.AreEqual(currentCulture_Initial, currentUICulture_Initial);
				replacedert.AreEqual(currentCulture_Final, currentUICulture_Final);

				replacedert.AreEqual(string.IsNullOrWhiteSpace(language) ? null : language, currentCulture_Final?.Name);
				replacedert.AreEqual(string.IsNullOrWhiteSpace(language) ? null : language, currentUICulture_Final?.Name);

				replacedert.AreEqual(preferredLanguageChangedResult, string.IsNullOrWhiteSpace(language) ? null : language);
				replacedert.AreEqual(preferredLanguageChangedResult, currentCulture_Final?.Name);
				replacedert.AreEqual(preferredLanguageChangedResult, currentUICulture_Final?.Name);

				void HandlePreferredLanguageChanged(object? sender, string? e)
				{
					LanguageService.PreferredLanguageChanged -= HandlePreferredLanguageChanged;

					didPreferredLanguageChangeFire = true;
					preferredLanguageChangedTCS.SetResult(e);
				}
			}
		}

19 Source : AsyncNameDep.cs
with MIT License
from bUnit-dev

public void SetResult(string name)
		{
			var prevSource = completionSource;
			completionSource = new TaskCompletionSource<string>();
			prevSource.SetResult(name);
		}

19 Source : AsyncDataTest.cs
with MIT License
from bUnit-dev

[Fact]
    public void LoadDataAsync()
    {
      // Arrange
      using var ctx = new TestContext();
      var textService = new TaskCompletionSource<string>();
      var cut = ctx.RenderComponent<AsyncData>(parameters => parameters
        .Add(p => p.TextService, textService.Task)
      );

      // Act - set the awaited result from the text service
      textService.SetResult("Hello World");

      // Wait for state before continuing test
      cut.WaitForState(() => cut.Find("p").TextContent == "Hello World");

      // replacedert - verify result has been set
      cut.MarkupMatches("<p>Hello World</p>");
    }

19 Source : AsyncDataTest.cs
with MIT License
from bUnit-dev

[Fact]
    public void LoadDataAsyncWithTimeout()
    {
      // Arrange
      using var ctx = new TestContext();
      var textService = new TaskCompletionSource<string>();
      var cut = ctx.RenderComponent<AsyncData>(parameters => parameters
        .Add(p => p.TextService, textService.Task)
      );

      // Act - set the awaited result from the text service
      textService.SetResult("Long time");

      // Wait for state before continuing test
      cut.WaitForState(() => cut.Find("p").TextContent == "Long time", TimeSpan.FromSeconds(2));

      // replacedert - verify result has been set
      cut.MarkupMatches("<p>Long time</p>");
    }

19 Source : AsyncDataTest.cs
with MIT License
from bUnit-dev

[Fact]
    public void LoadDataAsyncreplacedertion()
    {
      // Arrange
      using var ctx = new TestContext();
      var textService = new TaskCompletionSource<string>();
      var cut = ctx.RenderComponent<AsyncData>(parameters => parameters
        .Add(p => p.TextService, textService.Task)
      );

      // Act - set the awaited result from the text service
      textService.SetResult("Hello World");

      // Wait for replacedertion to preplaced
      cut.WaitForreplacedertion(() => cut.MarkupMatches("<p>Hello World</p>"));
      cut.WaitForreplacedertion(() => cut.MarkupMatches("<p>Hello World</p>"), TimeSpan.FromSeconds(2));
    }

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

public Task<string> GetAsync(string key)
        {
            var tcs = new TaskCompletionSource<string>();
            if (!keyStore.TryGetValue(key, out var value))
                throw new Exception();
            tcs.SetResult(value);
            return tcs.Task;
        }

19 Source : RCON.cs
with MIT License
from Challengermode

private void RCONPacketReceived(RCONPacket packet)
        {
            // Call pending result and remove from map
            if (_pendingCommands.TryGetValue(packet.Id, out TaskCompletionSource<string> taskSource))
            {
                if (_multiPacket)
                {
                    //Read any previous messages 
                    string body;
                    _incomingBuffer.TryGetValue(packet.Id, out body);

                    if (packet.Body == "")
                    {
                        //Avoid yielding
                        taskSource.SetResult(body ?? string.Empty);
                        _pendingCommands.TryRemove(packet.Id, out _);
                        _incomingBuffer.Remove(packet.Id);
                    }
                    else
                    {
                        //Append to previous messages
                        _incomingBuffer[packet.Id] = body + packet.Body;
                    }
                }
                else
                {
                    //Avoid yielding
                    taskSource.SetResult(packet.Body);
                    _pendingCommands.TryRemove(packet.Id, out _);
                }
            }
        }

19 Source : RCON.cs
with MIT License
from Challengermode

private void RCONPacketReceived(RCONPacket packet)
        {
            // Call pending result and remove from map
            if (_pendingCommands.TryGetValue(packet.Id, out TaskCompletionSource<string> taskSource))
            {
                if (_multiPacket)
                {
                    //Read any previous messages 
                    string body;
                    _incomingBuffer.TryGetValue(packet.Id, out body);

                    if (packet.Body == "")
                    {
                        //Avoid yielding
                        taskSource.SetResult(body ?? string.Empty);
                        _pendingCommands.TryRemove(packet.Id, out _);
                        _incomingBuffer.Remove(packet.Id);
                    }
                    else
                    {
                        //Append to previous messages
                        _incomingBuffer[packet.Id] = body + packet.Body;
                    }
                }
                else
                {
                    //Avoid yielding
                    taskSource.SetResult(packet.Body);
                    _pendingCommands.TryRemove(packet.Id, out _);
                }
            }
        }

19 Source : RoundtripTime_Tests.cs
with MIT License
from chkr1011

[TestMethod]
        public async Task Round_Trip_Time()
        {
            using (var testEnvironment = new TestEnvironment(TestContext))
            {
                await testEnvironment.StartServer();
                var receiverClient = await testEnvironment.ConnectClient();
                var senderClient = await testEnvironment.ConnectClient();

                await receiverClient.SubscribeAsync("#");
                
                TaskCompletionSource<string> response = null;

                receiverClient.UseApplicationMessageReceivedHandler(e => 
                {
                    response?.SetResult(e.ApplicationMessage.ConvertPayloadToString());
                });

                var times = new List<TimeSpan>();
                var stopwatch = Stopwatch.StartNew();

                await Task.Delay(1000);

                for (var i = 0; i < 100; i++)
                {
                    response = new TaskCompletionSource<string>();
                    await senderClient.PublishAsync("test", DateTime.UtcNow.Ticks.ToString());
                    response.Task.GetAwaiter().GetResult();

                    stopwatch.Stop();
                    times.Add(stopwatch.Elapsed);
                    stopwatch.Restart();
                }
            }
        }

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

private static async Task<string> GetAsync(string url)
        {
            var xmlHttp = new XMLHttpRequest();
            xmlHttp.open("GET", url, true);

            xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*");

            var tcs = new TaskCompletionSource<string>();

            xmlHttp.onreadystatechange = (e) =>
            {
                if (xmlHttp.readyState == 0)
                {
                    tcs.SetException(new Exception("Request aborted"));
                }
                else if (xmlHttp.readyState == 4)
                {
                    if (xmlHttp.status == 200 || xmlHttp.status == 201 || xmlHttp.status == 304)
                    {
                        tcs.SetResult(xmlHttp.responseText);
                    }
                    else tcs.SetException(new Exception("Request failed"));
                }
            };

            xmlHttp.send();

            var tcsTask = tcs.Task;

            while (true)
            {
                await Task.WhenAny(tcsTask, Task.Delay(150));

                if (tcsTask.IsCompleted)
                {
                    if (tcsTask.IsFaulted)
                        throw tcsTask.Exception;
                    return tcsTask.Result;
                }
            }
        }

19 Source : BarcodeScannerController.cs
with MIT License
from dansiegel

public Task<string> ReadBarcodeAsync()
        {
            var tcs = new TaskCompletionSource<string>();
            ReadBarcodeInternal(r => tcs.SetResult(r.Text), e => tcs.SetException(e));
            return tcs.Task;
        }

19 Source : BarcodeScannerController.cs
with MIT License
from dansiegel

public Task<string> ReadBarcodeAsync(params BarcodeFormat[] barcodeFormats)
        {
            var initialFormats = _scannerView.ScannerView.Options.PossibleFormats;
            _scannerView.ScannerView.Options.PossibleFormats = new List<BarcodeFormat>(barcodeFormats);
            var tcs = new TaskCompletionSource<string>();
            ReadBarcodeInternal(r =>
            {
                _scannerView.ScannerView.Options.PossibleFormats = initialFormats;
                tcs.SetResult(r.Text);
            }, e => tcs.SetException(e));
            return tcs.Task;
        }

19 Source : HcsOperation.cs
with The Unlicense
from dantmnf

private void CompleteCallback(IntPtr handle, IntPtr context)
        {
            completed = true;
            try
            {
                var result = GetResult();
                tsc.SetResult(result);
            }
            catch (Exception e)
            {
                tsc.SetException(e);
            }
        }

19 Source : WebKitWebViewRenderer.cs
with MIT License
from dotnet

public void OnReceiveValue(Java.Lang.Object result)
            {
                if (_source == null)
                {
                    return;
                }

                var json = ((Java.Lang.String)result).ToString();
                _source.SetResult(json);
            }

19 Source : StatusHandler.cs
with MIT License
from dotnetGame

void IStatusHandler.OnResponse(Response response)
        {
            if (_pendingRequests.TryDequeue(out var tcs))
                tcs.SetResult(response.JsonResponse);
        }

19 Source : IMiniblinkHandle.cs
with Apache License 2.0
from duwenjie15

internal static void GetCookieCallback(mbWebView webview, IntPtr token, MbAsynRequestState state, string cookie)
        {
            if (s_getStringCallbackDict.TryRemove(token, out TaskCompletionSource<string> taskCompletionSource))
            {
                taskCompletionSource.SetResult(state == MbAsynRequestState.kMbAsynRequestStateOk ? cookie : null);
            }
        }

19 Source : IMiniblinkHandle.cs
with Apache License 2.0
from duwenjie15

internal static void GetSourceCallback(mbWebView webview, IntPtr token, string mhtml)
        {
            if (s_getStringCallbackDict.TryRemove(token, out TaskCompletionSource<string> taskCompletionSource))
            {
                taskCompletionSource.SetResult(mhtml);
            }
        }

19 Source : AutoUpdater.cs
with MIT License
from ElectronNET

public Task<string> DownloadUpdateAsync()
        {
            var taskCompletionSource = new TaskCompletionSource<string>();
            string guid = Guid.NewGuid().ToString();

            BridgeConnector.Socket.On("autoUpdaterDownloadUpdateComplete" + guid, (downloadedPath) =>
            {
                BridgeConnector.Socket.Off("autoUpdaterDownloadUpdateComplete" + guid);
                taskCompletionSource.SetResult(downloadedPath.ToString());
            });

            BridgeConnector.Socket.Emit("autoUpdaterDownloadUpdate", guid);

            return taskCompletionSource.Task;
        }

19 Source : AutoUpdater.cs
with MIT License
from ElectronNET

public Task<string> GetFeedURLAsync()
        {
            var taskCompletionSource = new TaskCompletionSource<string>();
            string guid = Guid.NewGuid().ToString();

            BridgeConnector.Socket.On("autoUpdaterGetFeedURLComplete" + guid, (downloadedPath) =>
            {
                BridgeConnector.Socket.Off("autoUpdaterGetFeedURLComplete" + guid);
                taskCompletionSource.SetResult(downloadedPath.ToString());
            });

            BridgeConnector.Socket.Emit("autoUpdaterGetFeedURL", guid);

            return taskCompletionSource.Task;
        }

19 Source : Clipboard.cs
with MIT License
from ElectronNET

public Task<string> ReadTextAsync(string type = "")
        {
            var taskCompletionSource = new TaskCompletionSource<string>();

            BridgeConnector.Socket.On("clipboard-readText-Completed", (text) =>
            {
                BridgeConnector.Socket.Off("clipboard-readText-Completed");

                taskCompletionSource.SetResult(text.ToString());
            });

            BridgeConnector.Socket.Emit("clipboard-readText", type);

            return taskCompletionSource.Task;
        }

19 Source : Clipboard.cs
with MIT License
from ElectronNET

public Task<string> ReadHTMLAsync(string type = "")
        {
            var taskCompletionSource = new TaskCompletionSource<string>();

            BridgeConnector.Socket.On("clipboard-readHTML-Completed", (text) =>
            {
                BridgeConnector.Socket.Off("clipboard-readHTML-Completed");

                taskCompletionSource.SetResult(text.ToString());
            });

            BridgeConnector.Socket.Emit("clipboard-readHTML", type);

            return taskCompletionSource.Task;
        }

19 Source : Clipboard.cs
with MIT License
from ElectronNET

public Task<string> ReadRTFAsync(string type = "")
        {
            var taskCompletionSource = new TaskCompletionSource<string>();

            BridgeConnector.Socket.On("clipboard-readRTF-Completed", (text) =>
            {
                BridgeConnector.Socket.Off("clipboard-readRTF-Completed");

                taskCompletionSource.SetResult(text.ToString());
            });

            BridgeConnector.Socket.Emit("clipboard-readRTF", type);

            return taskCompletionSource.Task;
        }

19 Source : Clipboard.cs
with MIT License
from ElectronNET

public Task<string> ReadFindTextAsync()
        {
            var taskCompletionSource = new TaskCompletionSource<string>();

            BridgeConnector.Socket.On("clipboard-readFindText-Completed", (text) =>
            {
                BridgeConnector.Socket.Off("clipboard-readFindText-Completed");

                taskCompletionSource.SetResult(text.ToString());
            });

            BridgeConnector.Socket.Emit("clipboard-readFindText");

            return taskCompletionSource.Task;
        }

19 Source : CommandLine.cs
with MIT License
from ElectronNET

public async Task<string> GetSwitchValueAsync(string switchName, CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();

            var taskCompletionSource = new TaskCompletionSource<string>();
            using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
            {
                BridgeConnector.Socket.On("appCommandLineGetSwitchValueCompleted", (result) =>
                {
                    BridgeConnector.Socket.Off("appCommandLineGetSwitchValueCompleted");
                    taskCompletionSource.SetResult((string)result);
                });

                BridgeConnector.Socket.Emit("appCommandLineGetSwitchValue", switchName);

                return await taskCompletionSource.Task.ConfigureAwait(false);
            }
        }

19 Source : Dialog.cs
with MIT License
from ElectronNET

public Task<string> ShowSaveDialogAsync(BrowserWindow browserWindow, SaveDialogOptions options)
        {
            var taskCompletionSource = new TaskCompletionSource<string>();
            string guid = Guid.NewGuid().ToString();

            BridgeConnector.Socket.On("showSaveDialogComplete" + guid, (filename) =>
            {
                BridgeConnector.Socket.Off("showSaveDialogComplete" + guid);

                taskCompletionSource.SetResult(filename.ToString());
            });

            BridgeConnector.Socket.Emit("showSaveDialog",
            JObject.FromObject(browserWindow, _jsonSerializer),
            JObject.FromObject(options, _jsonSerializer),
            guid);

            return taskCompletionSource.Task;
        }

19 Source : Dock.cs
with MIT License
from ElectronNET

public async Task<string> GetBadgeAsync(CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var taskCompletionSource = new TaskCompletionSource<string>();
            using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
            {
                BridgeConnector.Socket.On("dock-getBadge-completed", (text) =>
                {
                    BridgeConnector.Socket.Off("dock-getBadge-completed");
                    taskCompletionSource.SetResult((string) text);
                });

                BridgeConnector.Socket.Emit("dock-getBadge");

                return await taskCompletionSource.Task
                    .ConfigureAwait(false);
            }
        }

19 Source : Session.cs
with MIT License
from ElectronNET

public Task<string> GetUserAgent()
        {
            var taskCompletionSource = new TaskCompletionSource<string>();
            string guid = Guid.NewGuid().ToString();

            BridgeConnector.Socket.On("webContents-session-getUserAgent-completed" + guid, (userAgent) =>
            {
                BridgeConnector.Socket.Off("webContents-session-getUserAgent-completed" + guid);
                taskCompletionSource.SetResult(userAgent.ToString());
            });

            BridgeConnector.Socket.Emit("webContents-session-getUserAgent", Id, guid);

            return taskCompletionSource.Task;
        }

19 Source : Session.cs
with MIT License
from ElectronNET

public Task<string> ResolveProxyAsync(string url)
        {
            var taskCompletionSource = new TaskCompletionSource<string>();
            string guid = Guid.NewGuid().ToString();

            BridgeConnector.Socket.On("webContents-session-resolveProxy-completed" + guid, (proxy) =>
            {
                BridgeConnector.Socket.Off("webContents-session-resolveProxy-completed" + guid);
                taskCompletionSource.SetResult(proxy.ToString());
            });

            BridgeConnector.Socket.Emit("webContents-session-resolveProxy", Id, url, guid);

            return taskCompletionSource.Task;
        }

19 Source : Shell.cs
with MIT License
from ElectronNET

public Task<string> OpenPathAsync(string path)
        {
            var taskCompletionSource = new TaskCompletionSource<string>();

            BridgeConnector.Socket.On("shell-openPathCompleted", (errorMessage) =>
            {
                BridgeConnector.Socket.Off("shell-openPathCompleted");

                taskCompletionSource.SetResult((string) errorMessage);
            });

            BridgeConnector.Socket.Emit("shell-openPath", path);

            return taskCompletionSource.Task;
        }

19 Source : Shell.cs
with MIT License
from ElectronNET

public Task<string> OpenExternalAsync(string url, OpenExternalOptions options)
        {
            var taskCompletionSource = new TaskCompletionSource<string>();

            BridgeConnector.Socket.On("shell-openExternalCompleted", (error) =>
            {
                BridgeConnector.Socket.Off("shell-openExternalCompleted");

                taskCompletionSource.SetResult((string) error);
            });

            if (options == null)
            {
                BridgeConnector.Socket.Emit("shell-openExternal", url);
            }
            else
            {
                BridgeConnector.Socket.Emit("shell-openExternal", url, JObject.FromObject(options, _jsonSerializer));
            }

            return taskCompletionSource.Task;
        }

19 Source : WebContents.cs
with MIT License
from ElectronNET

public Task<string> GetUrl()
        {
            var taskCompletionSource = new TaskCompletionSource<string>();

            var eventString = "webContents-getUrl" + Id;
            BridgeConnector.Socket.On(eventString, (url) =>
            {
                BridgeConnector.Socket.Off(eventString);
                taskCompletionSource.SetResult((string)url);
            });

            BridgeConnector.Socket.Emit("webContents-getUrl", Id);

            return taskCompletionSource.Task;
        }

19 Source : FirebaseAnalyticsImplementation.cs
with MIT License
from f-miyu

public Task<string> GetAppInstanceIdAsync()
        {
            var tcs = new TaskCompletionSource<string>();

            replacedyticsProvider.Getreplacedytics().GetAppInstanceId().AddOnCompleteListener(new OnCompleteHandlerListener(task =>
            {
                if (task.IsSuccessful)
                {
                    tcs.SetResult(task.Result.ToString()!);
                }
                else
                {
                    tcs.SetException(task.Exception);
                }
            }));

            return tcs.Task;
        }

See More Examples