System.Threading.Tasks.Task.Yield()

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

1065 Examples 7

19 View Source File : IntegrationTest.cs
License : MIT License
Project Creator : 0x1000000

public static async Task<int> Error(int id)
        {
            await Task.Yield();
            throw new Exception("This is a test error #" + id);
        }

19 View Source File : Startup.cs
License : MIT License
Project Creator : 2881099

[Custom]
        async public virtual Task<string> GetAsync(string key)
        {
            await Task.Yield();
            return $"CustomRepository.GetAsync({key}) value";
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

[Cache(Key = "GetAsync")]
    [Cache2(Key = "GetAsync")]
    async public virtual Task<string> GetAsync()
    {
        await Task.Yield();
        return "MyClreplaced.GetAsync value";
    }

19 View Source File : DefatultAlipayHelper.cs
License : MIT License
Project Creator : 52ABP

public async Task<WebPayOutput> WebPay(WebPayInput input, AlipayOptions options = null)
        {
            await Task.Yield();

            if (input.Data.ProductCode.IsNullOrWhiteSpace())
            {
                input.Data.ProductCode = YoYoAlipayConsts.ProductCode_FAST_INSTANT_TRADE_PAY;
            }


            var request = new AlipayTradePagePayRequest();

            // 设置同步回调地址
            request.SetReturnUrl(input.SynchronizationCallbackUrl);
            // 设置异步通知接收地址
            request.SetNotifyUrl(input.AsyncNotifyUrl);
            // 将业务model载入到request
            request.SetBizModel(input.Data);

            // 发起支付
            var response = this._alipayService.SdkExecute(request);

            // 返回回调地址
            var tmpOptions = options ?? _alipayService.Options;

            return new WebPayOutput()
            {
                Response = response,
                RedirectUrl = $"{tmpOptions.Gatewayurl}?{response.Body}"
            };
        }

19 View Source File : DefatultAlipayHelper.cs
License : MIT License
Project Creator : 52ABP

public async Task<WapPayOutput> WapPay(WapPayInput input, AlipayOptions options = null)
        {
            await Task.Yield();

            // 设置产品代码
            if (input.Data.ProductCode.IsNullOrWhiteSpace())
            {
                input.Data.ProductCode = YoYoAlipayConsts.ProductCode_QUICK_WAP_WAY;
            }
            // 设置支付中途退出返回商户网站地址
            if (input.Data.QuitUrl.IsNullOrWhiteSpace())
            {
                input.Data.QuitUrl = input.QuitUrl;
            }

            var request = new AlipayTradeWapPayRequest();
            // 设置同步回调地址
            request.SetReturnUrl(input.SynchronizationCallbackUrl);
            // 设置异步通知接收地址
            request.SetNotifyUrl(input.AsyncNotifyUrl);
            // 将业务model载入到request
            request.SetBizModel(input.Data);

            // 发起支付
            var response = await this._alipayService.PageExecuteAsync(request);

            return new WapPayOutput()
            {
                Response = response,
                Body = response.Body
            };
        }

19 View Source File : DefatultAlipayHelper.cs
License : MIT License
Project Creator : 52ABP

public async Task<PayRequestCheckOutput> PayRequestCheck(HttpRequest request)
        {
            await Task.Yield();

            var result = new PayRequestCheckOutput();

            if (request.Method.ToLower() == "post")
            {
                result.SArray = GetRequestPost(request);
            }
            else
            {
                result.SArray = GetRequestGet(request);
            }

            if (result.SArray.Count != 0)
            {
                result.IsSuccess = _alipayService.RSACheckV1(result.SArray);
            }

            return result;
        }

19 View Source File : RecordStream.cs
License : MIT License
Project Creator : a1q123456

[RpcMethod("seek")]
        public async Task Seek([FromOptionalArgument] double milliSeconds)
        {
            var resetData = new AmfObject
            {
                {"level", "status" },
                {"code", "NetStream.Seek.Notify" },
                {"description", "Seeking stream." },
                {"details", "seek" }
            };
            var resetStatus = RtmpSession.CreateCommandMessage<OnStatusCommandMessage>();
            resetStatus.InfoObject = resetData;
            await MessageStream.SendMessageAsync(ChunkStream, resetStatus);

            _playCts?.Cancel();
            while (_playing == 1)
            {
                await Task.Yield();
            }

            var cts = new CancellationTokenSource();
            _playCts?.Dispose();
            _playCts = cts;
            await SeekAndPlay(milliSeconds, cts.Token);
        }

19 View Source File : RecordStream.cs
License : MIT License
Project Creator : a1q123456

[RpcMethod("pause")]
        public async Task Pause([FromOptionalArgument] bool isPause, [FromOptionalArgument] double milliseconds)
        {
            if (isPause)
            {
                _playCts?.Cancel();
                while (_playing == 1)
                {
                    await Task.Yield();
                }
            }
            else
            {
                var cts = new CancellationTokenSource();
                _playCts?.Dispose();
                _playCts = cts;
                await SeekAndPlay(milliseconds, cts.Token);
            }
        }

19 View Source File : RecordStream.cs
License : MIT License
Project Creator : a1q123456

private async Task StartPlayNoLock(CancellationToken ct)
        {
            while (_recordFile.Position < _recordFile.Length && !ct.IsCancellationRequested)
            {
                while (_bufferMs != -1 && _currentTimestamp >= _bufferMs)
                {
                    await Task.Yield();
                }

                await PlayRecordFileNoLock(ct);
            }
        }

19 View Source File : EventBusRabbitMq.cs
License : MIT License
Project Creator : Abdulrhman5

private async Task ProcessEvent(string eventName, string message)
        {
            _logger.LogTrace("Processing RabbitMQ event: {EventName}", eventName);

            if (_subsManager.HreplacedubscriptionsForEvent(eventName))
            {

                var subscriptions = _subsManager.GetHandlersForEvent(eventName);
                foreach (var subscription in subscriptions)
                {

                    var handler = _container.Resolve(subscription.HandlerType);
                    if (handler == null) continue;
                    var eventType = _subsManager.GetEventTypeByName(eventName);
                    var integrationEvent = JsonConvert.DeserializeObject(message, eventType);
                    var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);

                    await Task.Yield();
                    await (Task)concreteType.GetMethod(nameof(IIntegrationEventHandler<object>.HandleEvent)).Invoke(handler, new object[] { integrationEvent });
                }
            }
            else
            {
                _logger.LogWarning("No subscription for RabbitMQ event: {EventName}", eventName);
            }
        }

19 View Source File : MixedRealitySearchUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static async Task SearchProfileField(UnityEngine.Object profile, SearchConfig config, List<ProfileSearchResult> searchResults)
        {
            await Task.Yield();

            // The result that we will return, if not empty
            ProfileSearchResult result = new ProfileSearchResult();
            result.Profile = profile;
            BaseMixedRealityProfile baseProfile = (profile as BaseMixedRealityProfile);
            result.IsCustomProfile = (baseProfile != null) ? baseProfile.IsCustomProfile : false;
            searchResults.Add(result);

            // Go through the profile's serialized fields
            foreach (SerializedProperty property in GatherProperties(profile))
            {
                if (CheckFieldForProfile(property))
                {
                    await SearchProfileField(property.objectReferenceValue, config, searchResults);
                }
                else
                {
                    CheckFieldForKeywords(property, config, result);
                }
            }
           
            if (result.Fields.Count > 0)
            {
                result.Fields.Sort(delegate (FieldSearchResult r1, FieldSearchResult r2)
                {
                    if (r1.MatchStrength != r2.MatchStrength)
                    {
                        return r2.MatchStrength.CompareTo(r1.MatchStrength);
                    }
                    return r2.Property.name.CompareTo(r1.Property.name);
                });
            }
        }

19 View Source File : ProgressIndicatorLoadingBar.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public async Task OpenAsync()
        {
            if (state != ProgressIndicatorState.Closed)
            {
                throw new System.Exception("Can't open in state " + state);
            }

            smoothProgress = 0;
            lastSmoothProgress = 0;

            gameObject.SetActive(true);

            state = ProgressIndicatorState.Opening;

            await Task.Yield();

            state = ProgressIndicatorState.Open;
        }

19 View Source File : ProgressIndicatorLoadingBar.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public async Task CloseAsync()
        {
            if (state != ProgressIndicatorState.Open)
            {
                throw new System.Exception("Can't close in state " + state);
            }

            state = ProgressIndicatorState.Closing;

            await Task.Yield();

            state = ProgressIndicatorState.Closed;

            gameObject.SetActive(false);
        }

19 View Source File : ProgressIndicatorLoadingBar.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public async Task AwaitTransitionAsync()
        {
            while (isActiveAndEnabled)
            {
                switch (state)
                {
                    case ProgressIndicatorState.Open:
                    case ProgressIndicatorState.Closed:
                        return;

                    default:
                        break;
                }

                await Task.Yield();
            }
        }

19 View Source File : ProgressIndicatorObjectDisplay.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public async Task OpenAsync()
        {
            if (openCurve.length == 0)
            {
                Debug.LogWarning("Open curve length is zero - this may result in an infinite loop.");
            }

            float maxScale = openCurve.Evaluate(Mathf.Infinity);
            if (maxScale < 1f)
            {
                Debug.LogWarning("Open curve value never reaches 1 - this may result in an infinite loop.");
            }

            if (state != ProgressIndicatorState.Closed)
            {
                throw new System.Exception("Can't open in state " + state);
            }

            gameObject.SetActive(true);

            Reset();

            state = ProgressIndicatorState.Opening;

            float startTime = Time.unscaledTime;
            float openScale = 0f;
            while (openScale < 1)
            {
                openScale = openCurve.Evaluate(Time.unscaledTime - startTime);
                scaleTargetObject.transform.localScale = Vector3.one * currentScale * openScale;
                await Task.Yield();
            }

            state = ProgressIndicatorState.Open;
        }

19 View Source File : ProgressIndicatorObjectDisplay.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public async Task CloseAsync()
        {
            if (closeCurve.length == 0)
            {
                Debug.LogWarning("Open curve length is zero - this may result in an infinite loop.");
            }

            float minScale = closeCurve.Evaluate(Mathf.Infinity);
            if (minScale > 0)
            {
                Debug.LogWarning("Open curve value never reaches 0 - this may result in an infinite loop.");
            }

            if (state != ProgressIndicatorState.Open)
            {
                throw new System.Exception("Can't close in state " + state);
            }

            state = ProgressIndicatorState.Closing;

            float startTime = Time.unscaledTime;
            float closeScale = 1f;
            while (closeScale > 0)
            {
                closeScale = closeCurve.Evaluate(Time.unscaledTime - startTime);
                scaleTargetObject.transform.localScale = Vector3.one * currentScale * closeScale;
                await Task.Yield();
            }

            state = ProgressIndicatorState.Closed;

            gameObject.SetActive(false);
        }

19 View Source File : ProgressIndicatorOrbsRotator.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public async Task OpenAsync()
        {
            if (state != ProgressIndicatorState.Closed)
            {
                throw new System.Exception("Can't open in state " + state);
            }

            gameObject.SetActive(true);

            state = ProgressIndicatorState.Opening;

            StartOrbs();

            await Task.Yield();

            state = ProgressIndicatorState.Open;
        }

19 View Source File : ProgressIndicatorOrbsRotator.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public async Task CloseAsync()
        {
            if (state != ProgressIndicatorState.Open)
            {
                throw new System.Exception("Can't close in state " + state);
            }

            state = ProgressIndicatorState.Closing;

            StopOrbs();

            while (!hasAnimationFinished)
            {
                await Task.Yield();
            }

            state = ProgressIndicatorState.Closed;

            gameObject.SetActive(false);
        }

19 View Source File : CanRunAsyncSteps.cs
License : Microsoft Public License
Project Creator : achimismaili

public async Task AndThenBddfyShouldCaptureExceptionsThrownInAsyncMethod()
        {
            await Task.Yield();
            throw new Exception("Exception in async void method!!");
        }

19 View Source File : MessageListenerL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void GetNextMessage()
        {
            using (TestHostContext tc = CreateTestContext())
            using (var tokenSource = new CancellationTokenSource())
            {
                Tracing trace = tc.GetTrace();

                // Arrange.
                var expectedSession = new TaskAgentSession();
                PropertyInfo sessionIdProperty = expectedSession.GetType().GetProperty("SessionId", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                replacedert.NotNull(sessionIdProperty);
                sessionIdProperty.SetValue(expectedSession, Guid.NewGuid());

                _runnerServer
                    .Setup(x => x.CreateAgentSessionAsync(
                        _settings.PoolId,
                        It.Is<TaskAgentSession>(y => y != null),
                        tokenSource.Token))
                    .Returns(Task.FromResult(expectedSession));

                _credMgr.Setup(x => x.LoadCredentials()).Returns(new VssCredentials());
                _store.Setup(x => x.GetCredentials()).Returns(new CredentialData() { Scheme = Constants.Configuration.OAuthAccessToken });
                _store.Setup(x => x.GetMigratedCredentials()).Returns(default(CredentialData));

                // Act.
                MessageListener listener = new MessageListener();
                listener.Initialize(tc);

                bool result = await listener.CreateSessionAsync(tokenSource.Token);
                replacedert.True(result);

                var arMessages = new TaskAgentMessage[]
                {
                        new TaskAgentMessage
                        {
                            Body = "somebody1",
                            MessageId = 4234,
                            MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
                        },
                        new TaskAgentMessage
                        {
                            Body = "somebody2",
                            MessageId = 4235,
                            MessageType = JobCancelMessage.MessageType
                        },
                        null,  //should be skipped by GetNextMessageAsync implementation
                        null,
                        new TaskAgentMessage
                        {
                            Body = "somebody3",
                            MessageId = 4236,
                            MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
                        }
                };
                var messages = new Queue<TaskAgentMessage>(arMessages);

                _runnerServer
                    .Setup(x => x.GetAgentMessageAsync(
                        _settings.PoolId, expectedSession.SessionId, It.IsAny<long?>(), tokenSource.Token))
                    .Returns(async (Int32 poolId, Guid sessionId, Int64? lastMessageId, CancellationToken cancellationToken) =>
                    {
                        await Task.Yield();
                        return messages.Dequeue();
                    });
                TaskAgentMessage message1 = await listener.GetNextMessageAsync(tokenSource.Token);
                TaskAgentMessage message2 = await listener.GetNextMessageAsync(tokenSource.Token);
                TaskAgentMessage message3 = await listener.GetNextMessageAsync(tokenSource.Token);
                replacedert.Equal(arMessages[0], message1);
                replacedert.Equal(arMessages[1], message2);
                replacedert.Equal(arMessages[4], message3);

                //replacedert
                _runnerServer
                    .Verify(x => x.GetAgentMessageAsync(
                        _settings.PoolId, expectedSession.SessionId, It.IsAny<long?>(), tokenSource.Token), Times.Exactly(arMessages.Length));
            }
        }

19 View Source File : DotNetFrameworkTests.cs
License : MIT License
Project Creator : adamant

private static async Task<int> GetValueAsync(Func<Task<int>> task)
        {
            await Task.Yield();
            return await task().ConfigureAwait(false);
        }

19 View Source File : MaterialSwapper.cs
License : GNU General Public License v3.0
Project Creator : affederaffe

public async void Initialize()
        {
            Material? darkEnvSimpleMaterial = null;
            Material? transparentGlowMaterial = null;
            Material? opaqueGlowMaterial = null;
            while (darkEnvSimpleMaterial is null || transparentGlowMaterial is null || opaqueGlowMaterial is null)
            {
                await Task.Yield();
                Material[] materials = Resources.FindObjectsOfTypeAll<Material>();
                darkEnvSimpleMaterial ??= materials.FirstOrDefault(x => x.name == "DarkEnvironmentSimple");
                transparentGlowMaterial ??= materials.FirstOrDefault(x => x.name == "EnvLight");
                opaqueGlowMaterial ??= materials.FirstOrDefault(x => x.name == "EnvLightOpaque");
            }

            opaqueGlowMaterial.DisableKeyword("ENABLE_HEIGHT_FOG");
            transparentGlowMaterial.DisableKeyword("ENABLE_HEIGHT_FOG");
            _taskSource.SetResult((darkEnvSimpleMaterial, transparentGlowMaterial, opaqueGlowMaterial));
        }

19 View Source File : PackageServiceTests.cs
License : MIT License
Project Creator : ai-traders

[Theory]
            [MemberData(nameof(ReturnsPackageData))]
            public async Task ReturnsPackage(string packageId, string packageVersion, bool includeUnlisted, bool exists)
            {
                // TODO: Ensure resulting versions are normalized.
                await Task.Yield();
            }

19 View Source File : PackageServiceTests.cs
License : MIT License
Project Creator : ai-traders

[Fact]
            public async Task ReturnsFalseIfPackageDoesNotExist()
            {
                await Task.Yield();
            }

19 View Source File : PackageServiceTests.cs
License : MIT License
Project Creator : ai-traders

[Theory]
            [InlineData(false)]
            [InlineData(true)]
            public async Task UnlistsPackage(bool listed)
            {
                // TODO: This should succeed if the package is unlisted.
                // TODO: Returns true
                await Task.Yield();
            }

19 View Source File : PackageServiceTests.cs
License : MIT License
Project Creator : ai-traders

[Theory]
            [InlineData(false)]
            [InlineData(true)]
            public async Task RelistsPackage(bool listed)
            {
                // TODO: This should succeed if the package is listed.
                // TODO: Return true
                await Task.Yield();
            }

19 View Source File : PackageServiceTests.cs
License : MIT License
Project Creator : ai-traders

[Fact]
            public async Task IncrementsPackageDownloads()
            {
                await Task.Yield();
            }

19 View Source File : PackageServiceTests.cs
License : MIT License
Project Creator : ai-traders

[Fact]
            public async Task DeletesPackage()
            {
                await Task.Yield();
            }

19 View Source File : AsyncTestSuite.cs
License : MIT License
Project Creator : ahydrax

public async Task AsyncAtomTest()
        {
            await Task.Yield();

            var client = new BackgroundJobClient(JobStorage.Current);

            var atomId = client.Enqueue("atom-async", builder =>
            {
                var job1 = builder.Enqueue(() => AsyncWait(5000));
                var job2 = builder.Enqueue(() => AsyncWait(3000));
                var job3 = builder.ContinueJobWith(job2, () => AsyncWait(2000));
                var job4 = builder.Schedule(() => AsyncWait(3000), DateTime.UtcNow.AddSeconds(5));
                var job5 = builder.ContinueJobWith(job4, () => AsyncWait(3000));
            });

            client.ContinueJobWith(atomId, () => Done());
        }

19 View Source File : AsyncTestSuite.cs
License : MIT License
Project Creator : ahydrax

public async Task AsyncAtomTest2()
        {
            await Task.Yield();

            var client = new BackgroundJobClient(JobStorage.Current);

            var atomId = client.Enqueue("atom-async", builder =>
            {
                for (var i = 0; i < 150; i++)
                {
                    builder.Enqueue(() => AsyncWaitOrException(1000));
                }
            });

            client.ContinueJobWith(atomId, () => Done());
        }

19 View Source File : PackageServiceTests.cs
License : MIT License
Project Creator : ai-traders

[Fact]
            public async Task ReturnsPackageAlreadyExistsOnUniqueConstraintViolation()
            {
                await Task.Yield();
            }

19 View Source File : PackageServiceTests.cs
License : MIT License
Project Creator : ai-traders

[Fact]
            public async Task AddsPackage()
            {
                // TODO: Returns Success
                // TODO: Adds package
                await Task.Yield();
            }

19 View Source File : PackageServiceTests.cs
License : MIT License
Project Creator : ai-traders

[Theory]
            [InlineData("Package", "1.0.0", true)]
            [InlineData("Package", "1.0.0.0", true)]
            [InlineData("Unlisted.Package", "1.0.0", true)]
            [InlineData("Fake.Package", "1.0.0", false)]
            public async Task ReturnsTrueIfPackageExists(string packageId, string packageVersion, bool exists)
            {
                await Task.Yield();
            }

19 View Source File : PackageServiceTests.cs
License : MIT License
Project Creator : ai-traders

[Fact]
            public async Task ReturnsEmptyListIfPackageDoesNotExist()
            {
                // Ensure the context has packages with a different id/version
                await Task.Yield();
            }

19 View Source File : PackageServiceTests.cs
License : MIT License
Project Creator : ai-traders

[Theory]
            [MemberData(nameof(ReturnsPackagesData))]
            public async Task ReturnsPackages(string packageId, string packageVersion, bool includeUnlisted, bool exists)
            {
                // TODO: Ensure resulting versions are normalized.
                await Task.Yield();
            }

19 View Source File : PackageServiceTests.cs
License : MIT License
Project Creator : ai-traders

[Fact]
            public async Task ReturnsNullIfPackageDoesNotExist()
            {
                await Task.Yield();
            }

19 View Source File : RateLimitBucket.cs
License : MIT License
Project Creator : Aiko-IT-Systems

internal async Task TryResetLimitAsync(DateTimeOffset now)
        {
            if (this.ResetAfter.HasValue)
                this.ResetAfter = this.ResetAfterOffset - now;

            if (this._nextReset == 0)
                return;

            if (this._nextReset > now.UtcTicks)
                return;

            while (Interlocked.CompareExchange(ref this._limitResetting, 1, 0) != 0)
#pragma warning restore 420
                await Task.Yield();

            if (this._nextReset != 0)
            {
                this._remaining = this.Maximum;
                this._nextReset = 0;
            }

            this._limitResetting = 0;
        }

19 View Source File : RestClient.cs
License : MIT License
Project Creator : Aiko-IT-Systems

private async Task<TaskCompletionSource<bool>> WaitForInitialRateLimit(RateLimitBucket bucket)
        {
            while (!bucket._limitValid)
            {
                if (bucket._limitTesting == 0)
                {
                    if (Interlocked.CompareExchange(ref bucket._limitTesting, 1, 0) == 0)
                    {
                        // if we got here when the first request was just finishing, we must not create the waiter task as it would signel ExecureRequestAsync to bypreplaced rate limiting
                        if (bucket._limitValid)
                            return null;

                        // allow exactly one request to go through without having rate limits available
                        var ratelimitsTcs = new TaskCompletionSource<bool>();
                        bucket._limitTestFinished = ratelimitsTcs.Task;
                        return ratelimitsTcs;
                    }
                }
                // it can take a couple of cycles for the task to be allocated, so wait until it happens or we are no longer probing for the limits
                Task waitTask = null;
                while (bucket._limitTesting != 0 && (waitTask = bucket._limitTestFinished) == null)
                    await Task.Yield();
                if (waitTask != null)
                    await waitTask.ConfigureAwait(false);

                // if the request failed and the response did not have rate limit headers we have allow the next request and wait again, thus this is a loop here
            }
            return null;
        }

19 View Source File : PaginationRequest.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public async Task SkipRightAsync()
        {
            await Task.Yield();

            this._index = this._pages.Count - 1;
        }

19 View Source File : WebSocketClient.cs
License : MIT License
Project Creator : Aiko-IT-Systems

internal async Task ReceiverLoopAsync()
        {
            await Task.Yield();

            var token = this._receiverToken;
            var buffer = new ArraySegment<byte>(new byte[IncomingChunkSize]);

            try
            {
                using var bs = new MemoryStream();
                while (!token.IsCancellationRequested)
                {
                    // See https://github.com/RogueException/Discord.Net/commit/ac389f5f6823e3a720aedd81b7805adbdd78b66d
                    // for explanation on the cancellation token

                    WebSocketReceiveResult result;
                    byte[] resultBytes;
                    do
                    {
                        result = await this._ws.ReceiveAsync(buffer, CancellationToken.None).ConfigureAwait(false);

                        if (result.MessageType == WebSocketMessageType.Close)
                            break;

                        bs.Write(buffer.Array, 0, result.Count);
                    }
                    while (!result.EndOfMessage);

                    resultBytes = new byte[bs.Length];
                    bs.Position = 0;
                    bs.Read(resultBytes, 0, resultBytes.Length);
                    bs.Position = 0;
                    bs.SetLength(0);

                    if (!this._isConnected && result.MessageType != WebSocketMessageType.Close)
                    {
                        this._isConnected = true;
                        await this._connected.InvokeAsync(this, new SocketEventArgs(this._serviceProvider)).ConfigureAwait(false);
                    }

                    if (result.MessageType == WebSocketMessageType.Binary)
                    {
                        await this._messageReceived.InvokeAsync(this, new SocketBinaryMessageEventArgs(resultBytes)).ConfigureAwait(false);
                    }
                    else if (result.MessageType == WebSocketMessageType.Text)
                    {
                        await this._messageReceived.InvokeAsync(this, new SocketTextMessageEventArgs(Utilities.UTF8.GetString(resultBytes))).ConfigureAwait(false);
                    }
                    else // close
                    {
                        if (!this._isClientClose)
                        {
                            var code = result.CloseStatus.Value;
                            code = code == WebSocketCloseStatus.NormalClosure || code == WebSocketCloseStatus.EndpointUnavailable
                                ? (WebSocketCloseStatus)4000
                                : code;

                            await this._ws.CloseOutputAsync(code, result.CloseStatusDescription, CancellationToken.None).ConfigureAwait(false);
                        }

                        await this._disconnected.InvokeAsync(this, new SocketCloseEventArgs(this._serviceProvider) { CloseCode = (int)result.CloseStatus, CloseMessage = result.CloseStatusDescription }).ConfigureAwait(false);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                await this._exceptionThrown.InvokeAsync(this, new SocketErrorEventArgs(this._serviceProvider) { Exception = ex }).ConfigureAwait(false);
                await this._disconnected.InvokeAsync(this, new SocketCloseEventArgs(this._serviceProvider) { CloseCode = -1, CloseMessage = "" }).ConfigureAwait(false);
            }

            // Don't await or you deadlock
            // DisconnectAsync waits for this method
            _ = this.DisconnectAsync().ConfigureAwait(false);
        }

19 View Source File : PaginationRequest.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public async Task<Page> GetPageAsync()
        {
            await Task.Yield();

            return this._pages[this._index];
        }

19 View Source File : PaginationRequest.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public async Task NextPageAsync()
        {
            await Task.Yield();

            switch (this._behaviour)
            {
                case PaginationBehaviour.Ignore:
                    if (this._index == this._pages.Count - 1)
                        break;
                    else
                        this._index++;

                    break;

                case PaginationBehaviour.WrapAround:
                    if (this._index == this._pages.Count - 1)
                        this._index = 0;
                    else
                        this._index++;

                    break;
            }
        }

19 View Source File : PaginationRequest.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public async Task PreviousPageAsync()
        {
            await Task.Yield();

            switch (this._behaviour)
            {
                case PaginationBehaviour.Ignore:
                    if (this._index == 0)
                        break;
                    else
                        this._index--;

                    break;

                case PaginationBehaviour.WrapAround:
                    if (this._index == 0)
                        this._index = this._pages.Count - 1;
                    else
                        this._index--;

                    break;
            }
        }

19 View Source File : PaginationRequest.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public async Task<PaginationEmojis> GetEmojisAsync()
        {
            await Task.Yield();

            return this._emojis;
        }

19 View Source File : PaginationRequest.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public async Task<DiscordMessage> GetMessageAsync()
        {
            await Task.Yield();

            return this._message;
        }

19 View Source File : PaginationRequest.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public async Task<DiscordUser> GetUserAsync()
        {
            await Task.Yield();

            return this._user;
        }

19 View Source File : PaginationRequest.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public async Task<TaskCompletionSource<bool>> GetTaskCompletionSourceAsync()
        {
            await Task.Yield();

            return this._tcs;
        }

19 View Source File : PaginationRequest.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public async Task SkipLeftAsync()
        {
            await Task.Yield();

            this._index = 0;
        }

19 View Source File : NatsClientProtocol.cs
License : MIT License
Project Creator : AndyPook

private async Task ProcessOutbound(ChannelReader<NatsOperation> outboundReader, CancellationToken cancellationToken)
        {
            await Task.Yield();
            var opWriter = new NatsOperationWriter();

            try
            {
                await foreach (var op in outboundReader.ReadAllAsync(cancellationToken))
                {
                    opWriter.WriteMessage(op, connection.Transport.Output);

                    // add option for per-op flush
                    await connection.Transport.Output.FlushAsync(cancellationToken).ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException) { /* ignore cancellation */ }
            catch (IOException iox)
            {
                Console.WriteLine("outbound connection failed: " + iox.Message);
                operationHandler.ConnectionClosed();
            }
        }

19 View Source File : NatsClientProtocol.cs
License : MIT License
Project Creator : AndyPook

private async Task ProcessInbound(CancellationToken cancellationToken)
        {
            await Task.Yield();
            var protocolReader = connection.CreateReader();
            var opReader = new NatsOperationReader();

            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var result = await protocolReader.ReadAsync(opReader, cancellationToken).ConfigureAwait(false);
                    if (result.IsCompleted)
                    {
                        Console.WriteLine("inbound connection closed");
                        break;
                    }
                    protocolReader.Advance();

                    await operationHandler.HandleOperation(result.Message);
                }
                catch (OperationCanceledException) { /* ignore cancellation */ }
                catch (Exception)
                {
                    if (!connection.ConnectionClosed.IsCancellationRequested)
                        throw;
                    break;
                }
            }

            Console.WriteLine("!!! exit inbound");
            operationHandler.ConnectionClosed();
        }

See More Examples