System.Threading.Tasks.Task.FromException(System.Exception)

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

524 Examples 7

19 View Source File : AssertionSpecs.cs
License : MIT License
Project Creator : Tyrrrz

[Fact]
        public async Task I_can_replacedert_an_async_exception_and_get_no_error_if_the_expected_exception_is_thrown()
        {
            await Sutreplacedert.ThrowsAsync<IOException>(() => Task.FromException(new IOException()));
        }

19 View Source File : AssertionSpecs.cs
License : MIT License
Project Creator : Tyrrrz

[Fact]
        public async Task I_can_replacedert_an_async_exception_and_get_an_error_if_another_was_thrown()
        {
            await replacedert.ThrowsAsync<replacedertionException>(
                () => Sutreplacedert.ThrowsAsync<IOException>(() => Task.FromException(new FileNotFoundException()))
            );
        }

19 View Source File : AssertionSpecs.cs
License : MIT License
Project Creator : Tyrrrz

[Fact]
        public async Task I_can_replacedert_a_derived_async_exception_and_get_no_error_if_derived_exception_was_thrown()
        {
            await Sutreplacedert.ThrowsAsync<IOException>(() => Task.FromException(new FileNotFoundException()), true);
        }

19 View Source File : CurlHandler.cs
License : MIT License
Project Creator : ultranijia

protected internal override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest);
            }

            if (request.RequestUri.Scheme == UriSchemeHttps)
            {
                if (!s_supportsSSL)
                {
                    throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_https_support_unavailable_libcurl, CurlVersionDescription));
                }
            }
            else
            {
                Debug.replacedert(request.RequestUri.Scheme == UriSchemeHttp, "HttpClient expected to validate scheme as http or https.");
            }

            if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null))
            {
                return Task.FromException<HttpResponseMessage>(
                    new HttpRequestException(SR.net_http_client_execution_error,
                        new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content)));
            }

            if (_useCookies && _cookieContainer == null)
            {
                throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
            }

            CheckDisposed();
            SetOperationStarted();

            // Do an initial cancellation check to avoid initiating the async operation if
            // cancellation has already been requested.  After this, we'll rely on CancellationToken.Register
            // to notify us of cancellation requests and shut down the operation if possible.
            if (cancellationToken.IsCancellationRequested)
            {
                return Task.FromCanceled<HttpResponseMessage>(cancellationToken);
            }

            // Create the easy request.  This replacedociates the easy request with this handler and configures
            // it based on the settings configured for the handler.
            var easy = new EasyRequest(this, _agent, request, cancellationToken);
            try
            {
                EventSourceTrace("{0}", request, easy: easy);
                _agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New });
            }
            catch (Exception exc)
            {
                easy.CleanupAndFailRequest(exc);
            }

            return easy.Task;
        }

19 View Source File : CurlHandler.CurlResponseMessage.cs
License : MIT License
Project Creator : ultranijia

public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
            {
                CheckDisposed();

                EventSourceTrace("Buffer: {0}", buffer.Length);

                // Check for cancellation
                if (cancellationToken.IsCancellationRequested)
                {
                    EventSourceTrace("Canceled");
                    return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
                }

                lock (_lockObject)
                {
                    VerifyInvariants();

                    // If there's currently a pending read, fail this read, as we don't support concurrent reads.
                    if (_pendingReadRequest != null)
                    {
                        EventSourceTrace("Failing due to existing pending read; concurrent reads not supported.");
                        return new ValueTask<int>(Task.FromException<int>(new InvalidOperationException(SR.net_http_content_no_concurrent_reads)));
                    }

                    // If the stream was already completed with failure, complete the read as a failure.
                    if (_completed != null && _completed != s_completionSentinel)
                    {
                        EventSourceTrace("Failing read with error: {0}", _completed);

                        OperationCanceledException oce = _completed as OperationCanceledException;
                        return new ValueTask<int>((oce != null && oce.CancellationToken.IsCancellationRequested) ?
                            Task.FromCanceled<int>(oce.CancellationToken) :
                            Task.FromException<int>(MapToReadWriteIOException(_completed, isRead: true)));
                    }

                    // Quick check for if no data was actually requested.  We do this after the check
                    // for errors so that we can still fail the read and transfer the exception if we should.
                    if (buffer.Length == 0)
                    {
                        return new ValueTask<int>(0);
                    }

                    // If there's any data left over from a previous call, grab as much as we can.
                    if (_remainingDataCount > 0)
                    {
                        int bytesToCopy = Math.Min(buffer.Length, _remainingDataCount);
                        new Span<byte>(_remainingData, _remainingDataOffset, bytesToCopy).CopyTo(buffer.Span);

                        _remainingDataOffset += bytesToCopy;
                        _remainingDataCount -= bytesToCopy;
                        Debug.replacedert(_remainingDataCount >= 0, "The remaining count should never go negative");
                        Debug.replacedert(_remainingDataOffset <= _remainingData.Length, "The remaining offset should never exceed the buffer size");

                        EventSourceTrace("Read {0} bytes", bytesToCopy);
                        return new ValueTask<int>(bytesToCopy);
                    }

                    // If the stream has already been completed, complete the read immediately.
                    if (_completed == s_completionSentinel)
                    {
                        EventSourceTrace("Stream already completed");
                        return new ValueTask<int>(0);
                    }

                    // Finally, the stream is still alive, and we want to read some data, but there's no data 
                    // in the buffer so we need to register ourself to get the next write.
                    if (cancellationToken.CanBeCanceled)
                    {
                        // If the cancellation token is cancelable, then we need to register for cancellation.
                        // We create a special CancelableReadState that carries with it additional info:
                        // the cancellation token and the registration with that token.  When cancellation
                        // is requested, we schedule a work item that tries to remove the read state
                        // from being pending, canceling it in the process.  This needs to happen under the
                        // lock, which is why we schedule the operation to run asynchronously: if it ran
                        // synchronously, it could deadlock due to code on another thread holding the lock
                        // and calling Dispose on the registration concurrently with the call to Cancel
                        // the cancellation token.  Dispose on the registration won't return until the action
                        // replacedociated with the registration has completed, but if that action is currently
                        // executing and is blocked on the lock that's held while calling Dispose... deadlock.
                        var crs = new CancelableReadState(buffer, this, cancellationToken);
                        crs._registration = cancellationToken.Register(s1 =>
                        {
                            ((CancelableReadState)s1)._stream.EventSourceTrace("Cancellation invoked. Queueing work item to cancel read state");
                            Task.Factory.StartNew(s2 =>
                            {
                                var crsRef = (CancelableReadState)s2;
                                lock (crsRef._stream._lockObject)
                                {
                                    Debug.replacedert(crsRef._token.IsCancellationRequested, "We should only be here if cancellation was requested.");
                                    if (crsRef._stream._pendingReadRequest == crsRef)
                                    {
                                        crsRef._stream.EventSourceTrace("Canceling");
                                        crsRef.TrySetCanceled(crsRef._token);
                                        crsRef._stream.ClearPendingReadRequest();
                                    }
                                }
                            }, s1, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
                        }, crs);
                        _pendingReadRequest = crs;
                    }
                    else
                    {
                        // The token isn't cancelable.  Just create a normal read state.
                        _pendingReadRequest = new ReadState(buffer);
                    }

                    _easy._replacedociatedMultiAgent.RequestUnpause(_easy);
                    _easy._selfStrongToWeakReference.MakeStrong(); // convert from a weak to a strong ref to keep the easy alive during the read
                    return new ValueTask<int>(_pendingReadRequest.Task);
                }
            }

19 View Source File : CurlHandler.CurlResponseMessage.cs
License : MIT License
Project Creator : ultranijia

public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
            {
                CheckDisposed();

                EventSourceTrace("Buffer: {0}", buffer.Length);

                // Check for cancellation
                if (cancellationToken.IsCancellationRequested)
                {
                    EventSourceTrace("Canceled");
                    return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
                }

                lock (_lockObject)
                {
                    VerifyInvariants();

                    // If there's currently a pending read, fail this read, as we don't support concurrent reads.
                    if (_pendingReadRequest != null)
                    {
                        EventSourceTrace("Failing due to existing pending read; concurrent reads not supported.");
                        return new ValueTask<int>(Task.FromException<int>(new InvalidOperationException(SR.net_http_content_no_concurrent_reads)));
                    }

                    // If the stream was already completed with failure, complete the read as a failure.
                    if (_completed != null && _completed != s_completionSentinel)
                    {
                        EventSourceTrace("Failing read with error: {0}", _completed);

                        OperationCanceledException oce = _completed as OperationCanceledException;
                        return new ValueTask<int>((oce != null && oce.CancellationToken.IsCancellationRequested) ?
                            Task.FromCanceled<int>(oce.CancellationToken) :
                            Task.FromException<int>(MapToReadWriteIOException(_completed, isRead: true)));
                    }

                    // Quick check for if no data was actually requested.  We do this after the check
                    // for errors so that we can still fail the read and transfer the exception if we should.
                    if (buffer.Length == 0)
                    {
                        return new ValueTask<int>(0);
                    }

                    // If there's any data left over from a previous call, grab as much as we can.
                    if (_remainingDataCount > 0)
                    {
                        int bytesToCopy = Math.Min(buffer.Length, _remainingDataCount);
                        new Span<byte>(_remainingData, _remainingDataOffset, bytesToCopy).CopyTo(buffer.Span);

                        _remainingDataOffset += bytesToCopy;
                        _remainingDataCount -= bytesToCopy;
                        Debug.replacedert(_remainingDataCount >= 0, "The remaining count should never go negative");
                        Debug.replacedert(_remainingDataOffset <= _remainingData.Length, "The remaining offset should never exceed the buffer size");

                        EventSourceTrace("Read {0} bytes", bytesToCopy);
                        return new ValueTask<int>(bytesToCopy);
                    }

                    // If the stream has already been completed, complete the read immediately.
                    if (_completed == s_completionSentinel)
                    {
                        EventSourceTrace("Stream already completed");
                        return new ValueTask<int>(0);
                    }

                    // Finally, the stream is still alive, and we want to read some data, but there's no data 
                    // in the buffer so we need to register ourself to get the next write.
                    if (cancellationToken.CanBeCanceled)
                    {
                        // If the cancellation token is cancelable, then we need to register for cancellation.
                        // We create a special CancelableReadState that carries with it additional info:
                        // the cancellation token and the registration with that token.  When cancellation
                        // is requested, we schedule a work item that tries to remove the read state
                        // from being pending, canceling it in the process.  This needs to happen under the
                        // lock, which is why we schedule the operation to run asynchronously: if it ran
                        // synchronously, it could deadlock due to code on another thread holding the lock
                        // and calling Dispose on the registration concurrently with the call to Cancel
                        // the cancellation token.  Dispose on the registration won't return until the action
                        // replacedociated with the registration has completed, but if that action is currently
                        // executing and is blocked on the lock that's held while calling Dispose... deadlock.
                        var crs = new CancelableReadState(buffer, this, cancellationToken);
                        crs._registration = cancellationToken.Register(s1 =>
                        {
                            ((CancelableReadState)s1)._stream.EventSourceTrace("Cancellation invoked. Queueing work item to cancel read state");
                            Task.Factory.StartNew(s2 =>
                            {
                                var crsRef = (CancelableReadState)s2;
                                lock (crsRef._stream._lockObject)
                                {
                                    Debug.replacedert(crsRef._token.IsCancellationRequested, "We should only be here if cancellation was requested.");
                                    if (crsRef._stream._pendingReadRequest == crsRef)
                                    {
                                        crsRef._stream.EventSourceTrace("Canceling");
                                        crsRef.TrySetCanceled(crsRef._token);
                                        crsRef._stream.ClearPendingReadRequest();
                                    }
                                }
                            }, s1, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
                        }, crs);
                        _pendingReadRequest = crs;
                    }
                    else
                    {
                        // The token isn't cancelable.  Just create a normal read state.
                        _pendingReadRequest = new ReadState(buffer);
                    }

                    _easy._replacedociatedMultiAgent.RequestUnpause(_easy);
                    _easy._selfStrongToWeakReference.MakeStrong(); // convert from a weak to a strong ref to keep the easy alive during the read
                    return new ValueTask<int>(_pendingReadRequest.Task);
                }
            }

19 View Source File : RawConnectionStream.cs
License : MIT License
Project Creator : ultranijia

public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return new ValueTask(Task.FromCanceled(cancellationToken));
                }

                HttpConnection connection = _connection;
                if (connection == null)
                {
                    return new ValueTask(Task.FromException(new IOException(SR.ObjectDisposed_StreamClosed)));
                }

                if (buffer.Length == 0)
                {
                    return default;
                }

                ValueTask writeTask = connection.WriteWithoutBufferingAsync(buffer);
                return writeTask.IsCompleted ?
                    writeTask :
                    new ValueTask(WaitWithConnectionCancellationAsync(writeTask, connection, cancellationToken));
            }

19 View Source File : HttpClientTest.cs
License : MIT License
Project Creator : ultranijia

[Fact]
        public async Task GetContentAsync_SerializingContentThrows_Asynchronous_Throws()
        {
            var e = new FormatException();
            using (var client = new HttpClient(new CustomResponseHandler(
                (r, c) => Task.FromResult(new HttpResponseMessage() { Content = new CustomContent(stream => Task.FromException(e)) }))))
            {
                replacedert.Same(e, await replacedert.ThrowsAsync<FormatException>(() => client.GetStringAsync(CreateFakeUri())));
                replacedert.Same(e, await replacedert.ThrowsAsync<FormatException>(() => client.GetByteArrayAsync(CreateFakeUri())));
                replacedert.Same(e, await replacedert.ThrowsAsync<FormatException>(() => client.GetStreamAsync(CreateFakeUri())));
            }
        }

19 View Source File : SocketsHttpHandler.cs
License : MIT License
Project Creator : ultranijia

protected internal override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            CheckDisposed();
            HttpMessageHandler handler = _handler ?? SetupHandlerChain();

            Exception error = ValidateAndNormalizeRequest(request);
            if (error != null)
            {
                return Task.FromException<HttpResponseMessage>(error);
            }

            return handler.SendAsync(request, cancellationToken);
        }

19 View Source File : HttpContent.cs
License : MIT License
Project Creator : ultranijia

internal Task CopyToAsync(Stream stream, TransportContext context, CancellationToken cancellationToken)
        {
            CheckDisposed();
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            try
            {
                ArraySegment<byte> buffer;
                if (TryGetBuffer(out buffer))
                {
                    return CopyToAsyncCore(stream.WriteAsync(new ReadOnlyMemory<byte>(buffer.Array, buffer.Offset, buffer.Count), cancellationToken));
                }
                else
                {
                    Task task = SerializeToStreamAsync(stream, context, cancellationToken);
                    CheckTaskNotNull(task);
                    return CopyToAsyncCore(new ValueTask(task));
                }
            }
            catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e))
            {
                return Task.FromException(GetStreamCopyException(e));
            }
        }

19 View Source File : HttpContent.cs
License : MIT License
Project Creator : ultranijia

internal Task LoadIntoBufferAsync(long maxBufferSize, CancellationToken cancellationToken)
        {
            CheckDisposed();
            if (maxBufferSize > HttpContent.MaxBufferSize)
            {
                // This should only be hit when called directly; HttpClient/HttpClientHandler
                // will not exceed this limit.
                throw new ArgumentOutOfRangeException(nameof(maxBufferSize), maxBufferSize,
                    SR.Format(System.Globalization.CultureInfo.InvariantCulture,
                    SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize));
            }

            if (IsBuffered)
            {
                // If we already buffered the content, just return a completed task.
                return Task.CompletedTask;
            }

            Exception error = null;
            MemoryStream tempBuffer = CreateMemoryStream(maxBufferSize, out error);
            if (tempBuffer == null)
            {
                // We don't throw in LoadIntoBufferAsync(): return a faulted task.
                return Task.FromException(error);
            }

            try
            {
                Task task = SerializeToStreamAsync(tempBuffer, null, cancellationToken);
                CheckTaskNotNull(task);
                return LoadIntoBufferAsyncCore(task, tempBuffer);
            }
            catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e))
            {
                return Task.FromException(GetStreamCopyException(e));
            }
            // other synchronous exceptions from SerializeToStreamAsync/CheckTaskNotNull will propagate
        }

19 View Source File : StreamToStreamCopy.cs
License : MIT License
Project Creator : ultranijia

public static Task CopyAsync(Stream source, Stream destination, int bufferSize, bool disposeSource, CancellationToken cancellationToken = default(CancellationToken))
        {
            Debug.replacedert(source != null);
            Debug.replacedert(destination != null);
            Debug.replacedert(bufferSize >= 0);

            try
            {
                Task copyTask = bufferSize == 0 ?
                    source.CopyToAsync(destination, cancellationToken) :
                    source.CopyToAsync(destination, bufferSize, cancellationToken);

                if (!disposeSource)
                {
                    return copyTask;
                }

                switch (copyTask.Status)
                {
                    case TaskStatus.RanToCompletion:
                        DisposeSource(source);
                        return Task.CompletedTask;

                    case TaskStatus.Faulted:
                    case TaskStatus.Canceled:
                        return copyTask;

                    default:
                        return DisposeSourceAsync(copyTask, source);

                        static async Task DisposeSourceAsync(Task copyTask, Stream source)
                        {
                            await copyTask.ConfigureAwait(false);
                            DisposeSource(source);
                        }
                }
            }
            catch (Exception e)
            {
                // For compatibility with the previous implementation, catch everything (including arg exceptions) and
                // store errors into the task rather than letting them propagate to the synchronous caller.
                return Task.FromException(e);
            }
        }

19 View Source File : HttpClientTest.cs
License : MIT License
Project Creator : ultranijia

[Fact]
        public async Task GetAsync_CustomException_Asynchronous_ThrowsException()
        {
            var e = new FormatException();
            using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromException<HttpResponseMessage>(e))))
            {
                FormatException thrown = await replacedert.ThrowsAsync<FormatException>(() => client.GetAsync(CreateFakeUri()));
                replacedert.Same(e, thrown);
            }
        }

19 View Source File : LoggingAdviceTests.cs
License : MIT License
Project Creator : ValeraT1982

[Test]
        public void LogInfo_WhenTaskMethodCallWithException()
        {
            var testClreplaced = Subsreplacedute.For<ITestClreplaced>();
            testClreplaced.MethodWithTaskResult().Returns(Task.FromException(new Exception("ERROR!!!!")));
            var errorMreplacedages = new List<string>();
            var infoMreplacedages = new List<string>();
            var decorated = LoggingAdvice<ITestClreplaced>.Create(
                testClreplaced,
                s => infoMreplacedages.Add(s),
                s => errorMreplacedages.Add(s),
                o => o?.ToString(),
                _taskScheduler);

            replacedert.Throws<AggregateException>(() => decorated.MethodWithTaskResult().Wait());
            ReleaseContext();

            testClreplaced.Received().MethodWithTaskResult();
            replacedert.AreEqual(1, infoMreplacedages.Count);
            replacedert.AreEqual(1, errorMreplacedages.Count);
            replacedert.IsTrue(errorMreplacedages[0].Contains("ERROR!!!!"));
        }

19 View Source File : LoggingAdviceTests.cs
License : MIT License
Project Creator : ValeraT1982

[Test]
        public void LogInfo_WhenTaskWithResultThrowException()
        {
            var testClreplaced = Subsreplacedute.For<ITestClreplaced>();
            testClreplaced.MethodWithTaskStringResult().Returns(Task.FromException<string>(new Exception("ERROR!!!!")));
            var errorMreplacedages = new List<string>();
            var infoMreplacedages = new List<string>();
            var decorated = LoggingAdvice<ITestClreplaced>.Create(
                testClreplaced,
                s => infoMreplacedages.Add(s),
                s => errorMreplacedages.Add(s),
                o => o?.ToString(),
                _taskScheduler);

            replacedert.Throws<AggregateException>(() => decorated.MethodWithTaskStringResult().Wait());
            ReleaseContext();

            testClreplaced.Received().MethodWithTaskStringResult();
            replacedert.AreEqual(1, infoMreplacedages.Count);
            replacedert.AreEqual(1, errorMreplacedages.Count);
            replacedert.IsTrue(errorMreplacedages[0].Contains("ERROR!!!!"));
        }

19 View Source File : TupleExtensionTests.cs
License : MIT License
Project Creator : VictorGavrish

[Fact]
        public async Task TestWaitAllArgumentNullException()
        {
            // arrange
            var task1 = Task.FromResult(1);
            var task2 = Task.FromException<bool>(new ArgumentNullException());

            // act
            var exception = await Record.ExceptionAsync(async () => await (task1, task2).WhenAll());

            // replacedert
            replacedert.IsType<AggregateException>(exception);
            replacedert.IsType<ArgumentNullException>(((AggregateException)exception).InnerException);
        }

19 View Source File : LocalizationSourceBehaviour.cs
License : MIT License
Project Creator : vovgou

public virtual Task<Dictionary<string, object>> Load(CultureInfo cultureInfo)
            {
                Dictionary<string, object> dict = new Dictionary<string, object>();
                try
                {
                    if (source.Languages == null || source.Entries == null || source.Languages.Count <= 0 || source.Entries.Count <= 0)
                        return Task.FromResult(dict);

                    List<string> languages = source.Languages;
                    List<MultilingualEntry> entries = source.Entries;

                    string defaultName = "default";
                    string cultureISOName = cultureInfo.TwoLetterISOLanguageName;//eg:zh  en
                    string cultureName = cultureInfo.Name;//eg:zh-CN  en-US 

                    /* If the default column is not configured, the first data column is used as the default column */
                    if (!languages.Contains(defaultName))
                        defaultName = languages[0];

                    int defaultIndex = languages.IndexOf(defaultName);
                    if (defaultIndex >= 0)
                        FillData(dict, entries, defaultIndex);

                    int cultureISOIndex = languages.IndexOf(cultureISOName);
                    if (cultureISOIndex >= 0 && cultureISOIndex != defaultIndex)
                        FillData(dict, entries, cultureISOIndex);

                    int cultureIndex = languages.IndexOf(cultureName);
                    if (cultureIndex >= 0 && cultureIndex != defaultIndex && cultureIndex != cultureISOIndex)
                        FillData(dict, entries, cultureIndex);

                    return Task.FromResult(dict);
                }
                catch (Exception e)
                {
                    if (log.IsWarnEnabled)
                        log.WarnFormat("An error occurred when loading localized data from LocalizationSource \"{0}\".Error:{1}", this.name, e);
                    return Task.FromException<Dictionary<string, object>>(e);
                }
            }

19 View Source File : DefaultDataProvider.cs
License : MIT License
Project Creator : vovgou

public virtual Task<Dictionary<string, object>> Load(CultureInfo cultureInfo)
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            try
            {
                Textreplacedet[] defaultTexts = Resources.LoadAll<Textreplacedet>(GetDefaultPath()); //eg:default
                Textreplacedet[] twoLetterISOTexts = Resources.LoadAll<Textreplacedet>(GetPath(cultureInfo.TwoLetterISOLanguageName));//eg:zh  en
                Textreplacedet[] texts = cultureInfo.Name.Equals(cultureInfo.TwoLetterISOLanguageName) ? null : Resources.LoadAll<Textreplacedet>(GetPath(cultureInfo.Name));//eg:zh-CN  en-US

                FillData(dict, defaultTexts, cultureInfo);
                FillData(dict, twoLetterISOTexts, cultureInfo);
                FillData(dict, texts, cultureInfo);
                return Task.FromResult(dict);
            }
            catch (Exception e)
            {
                return Task.FromException<Dictionary<string, object>>(e);
            }
        }

19 View Source File : DefaultCsvDataProvider.cs
License : MIT License
Project Creator : vovgou

public Task<Dictionary<string, object>> Load(CultureInfo cultureInfo)
        {
            try
            {
                Dictionary<string, object> dict = new Dictionary<string, object>();
                Textreplacedet[] texts = Resources.LoadAll<Textreplacedet>(this.root);
                FillData(dict, texts, cultureInfo);
                return Task.FromResult(dict);
            }
            catch (Exception e)
            {
                return Task.FromException<Dictionary<string, object>>(e);
            }
        }

19 View Source File : AsyncTimerTest.cs
License : Apache License 2.0
Project Creator : VTPDevelopment

[Test]
		public void AsyncTimer_Does_Not_PropogateExceptions()
		{
			//Arrange
			using var timer = new AsyncTimer(() => Task.FromException<Exception>(new()), TimeSpan.FromSeconds(1));
			
			//Act
			var ex = replacedert.Catch(() => timer.Start());

			//replacedert
			replacedert.Null(ex);
		}

19 View Source File : AsyncTimerTest.cs
License : Apache License 2.0
Project Creator : VTPDevelopment

[Test]
		public void AsyncTimer_Fires_Errored_Event_On_Error()
		{
			//Arrange
			var errored = false;
			using var timer = new AsyncTimer(() => Task.FromException<Exception>(new()), TimeSpan.FromSeconds(1));
			timer.Errored += (_, _) => errored = true;
			
			//Act
			timer.Start();
			Thread.Sleep(100);
			//replacedert
			replacedert.True(errored);
		}

19 View Source File : AsyncTimerTest.cs
License : Apache License 2.0
Project Creator : VTPDevelopment

[Test]
		public void AsyncTimer_Fires_Errored_Event_On_Error_When_Yielding()
		{
			//Arrange
			var errored = false;
			using var timer = new AsyncTimer(() => Task.FromException<Exception>(new()), TimeSpan.FromSeconds(1));
			timer.Errored += (_, _) => errored = true;
			
			//Act
			timer.Start();
			Thread.Sleep(100);
			//replacedert
			replacedert.True(errored);
		}

19 View Source File : CS6_0.cs
License : GNU General Public License v3.0
Project Creator : wmjordan

public static async Task<string> MakeRequestAndLogFailures() {
			await Task.Delay(100);
			var streamTask = Task.FromResult("https://localHost:10000");
			try {
				return await streamTask;
			}
			catch (Exception e) when (e.Message.Contains("301")) {
				return await Task.FromException<string>(e);
			}
			finally {
				await Task.Delay(100);
			}
		}

19 View Source File : AuditPointExtensions.cs
License : GNU General Public License v2.0
Project Creator : yang-er

public static Task AuditAsync(this HttpContext context,
            string action, string? target, string? extra = null)
        {
            if (!context.Items.TryGetValue(nameof(AuditlogType), out object typer))
                return Task.FromException(new InvalidOperationException("No audit point specified."));
            int? cid = null;
            if (context.Items.TryGetValue(nameof(cid), out object cidd))
                cid = (int?)cidd;
            return AuditAsync(context,
                (AuditlogType)typer, cid, context.User.GetUserName() ?? "TOURIST",
                action, target, extra);
        }

See More Examples