System.Action.Invoke(System.Exception)

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

667 Examples 7

19 Source : BusinessInvokerBase.cs
with MIT License
from Avanade

protected override TResult WrapInvoke<TResult>(object caller, Func<TResult> func, BusinessInvokerArgs? param = null, [CallerMemberName] string? memberName = null, [CallerFilePath] string? filePath = null, [CallerLineNumber] int lineNumber = 0)
        {
            Check.NotNull(func, nameof(func));

            BusinessInvokerArgs bia = param ?? BusinessInvokerArgs.Default;
            TransactionScope? txn = null;
            OperationType ot = ExecutionContext.Current.OperationType;
            if (bia.OperationType.HasValue)
                ExecutionContext.Current.OperationType = bia.OperationType.Value;

            try
            {
                if (bia.IncludeTransactionScope)
                    txn = new TransactionScope(bia.TransactionScopeOption, TransactionScopeAsyncFlowOption.Enabled);

                var result = func();
                txn?.Complete();
                return result;
            }
            catch (Exception ex)
            {
                bia.ExceptionHandler?.Invoke(ex);
                throw;
            }
            finally
            {
                txn?.Dispose();
                ExecutionContext.Current.OperationType = ot;
            }
        }

19 Source : BusinessInvokerBase.cs
with MIT License
from Avanade

protected async override Task<TResult> WrapInvokeAsync<TResult>(object caller, Func<Task<TResult>> func, BusinessInvokerArgs? param = null, [CallerMemberName] string? memberName = null, [CallerFilePath] string? filePath = null, [CallerLineNumber] int lineNumber = 0)
        {
            Check.NotNull(func, nameof(func));

            BusinessInvokerArgs bia = Check.NotNull(param ?? BusinessInvokerArgs.Default, nameof(param));
            TransactionScope? txn = null;
            OperationType ot = ExecutionContext.Current.OperationType;
            if (bia.OperationType.HasValue)
                ExecutionContext.Current.OperationType = bia.OperationType.Value;

            try
            {
                if (bia.IncludeTransactionScope)
                    txn = new TransactionScope(bia.TransactionScopeOption, TransactionScopeAsyncFlowOption.Enabled);

                var result = await func().ConfigureAwait(false);
                txn?.Complete();
                return result;
            }
            catch (Exception ex)
            {
                bia.ExceptionHandler?.Invoke(ex);
                throw;
            }
            finally
            {
                txn?.Dispose();
                ExecutionContext.Current.OperationType = ot;
            }
        }

19 Source : DatabaseEventOutboxInvoker.cs
with MIT License
from Avanade

protected override TResult WrapInvoke<TResult>(object caller, Func<TResult> func, DatabaseEventOutboxInvokerArgs? param, [CallerMemberName] string? memberName = null, [CallerFilePath] string? filePath = null, [CallerLineNumber] int lineNumber = 0)
        {
            Check.NotNull(func, nameof(func));

            TransactionScope? txn = null;

            try
            {
                txn = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled);

                var result = func();
                PublishEventsToOutboxAsync(param).GetAwaiter().GetResult();

                txn?.Complete();
                return result;
            }
            catch (Exception ex)
            {
                param?.ExceptionHandler?.Invoke(ex);
                throw;
            }
            finally
            {
                txn?.Dispose();
            }
        }

19 Source : DatabaseEventOutboxInvoker.cs
with MIT License
from Avanade

protected async override Task<TResult> WrapInvokeAsync<TResult>(object caller, Func<Task<TResult>> func, DatabaseEventOutboxInvokerArgs? param, [CallerMemberName] string? memberName = null, [CallerFilePath] string? filePath = null, [CallerLineNumber] int lineNumber = 0)
        {
            Check.NotNull(func, nameof(func));

            TransactionScope? txn = null;

            try
            {
                txn = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled);

                var result = await func().ConfigureAwait(false);
                await PublishEventsToOutboxAsync(param).ConfigureAwait(false);

                txn?.Complete();
                return result;
            }
            catch (Exception ex)
            {
                param?.ExceptionHandler?.Invoke(ex);
                throw;
            }
            finally
            {
                txn?.Dispose();
            }
        }

19 Source : DatabaseEventOutboxInvoker.cs
with MIT License
from Avanade

protected override void WrapInvoke(object caller, Action action, DatabaseEventOutboxInvokerArgs? param, [CallerMemberName] string? memberName = null, [CallerFilePath] string? filePath = null, [CallerLineNumber] int lineNumber = 0)
        {
            Check.NotNull(action, nameof(action));

            TransactionScope? txn = null;

            try
            {
                txn = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled);

                action();
                PublishEventsToOutboxAsync(param).GetAwaiter().GetResult();

                txn?.Complete();
            }
            catch (Exception ex)
            {
                param?.ExceptionHandler?.Invoke(ex);
                throw;
            }
            finally
            {
                txn?.Dispose();
            }
        }

19 Source : DatabaseEventOutboxInvoker.cs
with MIT License
from Avanade

protected async override Task WrapInvokeAsync(object caller, Func<Task> func, DatabaseEventOutboxInvokerArgs? param, [CallerMemberName] string? memberName = null, [CallerFilePath] string? filePath = null, [CallerLineNumber] int lineNumber = 0)
        {
            Check.NotNull(func, nameof(func));

            TransactionScope? txn = null;

            try
            {
                txn = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled);

                await func().ConfigureAwait(false);
                await PublishEventsToOutboxAsync(param).ConfigureAwait(false);

                txn?.Complete();
            }
            catch (Exception ex)
            {
                param?.ExceptionHandler?.Invoke(ex);
                throw;
            }
            finally
            {
                txn?.Dispose();
            }
        }

19 Source : TaskExtensions.cs
with MIT License
from avikeid2007

public async static void AwaitAsync(this Task task, Action CompleteCallback, Action<Exception> ErrorCallback)
        {
            try
            {
                await task;
                CompleteCallback?.Invoke();
            }
            catch (Exception ex)
            {
                ErrorCallback?.Invoke(ex);
            }
        }

19 Source : TinySoup.cs
with MIT License
from awaescher

internal async Task<IList<AvailableVersion>> CallWebServiceAsync(string method, string parameterString)
        {
            HttpClient client;

            var uri = new Uri($"{URL}?method={method}&{parameterString}");

            var serializer = new DataContractJsonSerializer(typeof(List<AvailableVersion>));

            try
            {
                var proxyUri = new Uri(WebRequest.DefaultWebProxy.GetProxy(uri).AbsoluteUri);
                var directAccess = proxyUri?.Authority?.Equals(uri.Authority) == true;

                if (directAccess)
                {
                    client = new HttpClient();
                }
                else
                {
                    var proxy = new WebProxy()
                    {
                        Address = proxyUri,
                        BypreplacedProxyOnLocal = false,
                        UseDefaultCredentials = true
                    };
                    var httpClientHandler = new HttpClientHandler() { Proxy = proxy };
                    client = new HttpClient(handler: httpClientHandler, disposeHandler: true);
                }

                return serializer.ReadObject(await client.GetStreamAsync(uri).ConfigureAwait(false)) as List<AvailableVersion>;
            }
            catch (Exception ex)
            {
                _exceptionHandler?.Invoke(ex);
                return await Task.FromResult(new List<AvailableVersion>()).ConfigureAwait(false);
            }
        }

19 Source : TinySoup.cs
with MIT License
from awaescher

internal async Task<IList<AvailableVersion>> CallWebServiceAsync(string method, string parameterString)
		{
			try
			{
				HttpClient client;

				var uri = new Uri($"{URL}?method={method}&{parameterString}");

				var serializer = new DataContractJsonSerializer(typeof(List<AvailableVersion>));
				var proxyUri = new Uri(WebRequest.DefaultWebProxy.GetProxy(uri).AbsoluteUri);
				var directAccess = proxyUri?.Authority?.Equals(uri.Authority) == true;

				if (directAccess)
				{
					client = new HttpClient();
				}
				else
				{
					var proxy = new WebProxy()
					{
						Address = proxyUri,
						BypreplacedProxyOnLocal = false,
						UseDefaultCredentials = true
					};
					var httpClientHandler = new HttpClientHandler() { Proxy = proxy };
					client = new HttpClient(handler: httpClientHandler, disposeHandler: true);
				}

				return serializer.ReadObject(await client.GetStreamAsync(uri).ConfigureAwait(false)) as List<AvailableVersion>;
			}
			catch (Exception ex)
			{
				_exceptionHandler?.Invoke(ex);
				return await Task.FromResult(new List<AvailableVersion>()).ConfigureAwait(false);
			}
		}

19 Source : TinySoup.cs
with MIT License
from awaescher

internal async Task<IList<AvailableVersion>> CallWebServiceAsync(string method, string parameterString)
		{
			try
			{
				var targetUri = new Uri($"{URL}?method={method}&{parameterString}");
				var serializer = new DataContractJsonSerializer(typeof(List<AvailableVersion>));

				var handler = new HttpClientHandler();
				handler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
				var client = new HttpClient(handler, disposeHandler: true);

				return serializer.ReadObject(await client.GetStreamAsync(targetUri).ConfigureAwait(false)) as List<AvailableVersion>;
			}
			catch (Exception ex)
			{
				_exceptionHandler?.Invoke(ex);
				return await Task.FromResult(new List<AvailableVersion>()).ConfigureAwait(false);
			}
		}

19 Source : TaskQeury.cs
with MIT License
from awesomedotnetcore

private void Start()
        {
            Task.Factory.StartNew(() =>
            {
                while (_isRun)
                {
                    try
                    {
                        _semapreplaced.WaitOne();
                        bool success = _taskList.TryDequeue(out Action task);
                        if (success)
                        {
                            task?.Invoke();
                        }

                        if (_timeSpan != TimeSpan.Zero)
                            Thread.Sleep(_timeSpan);
                    }
                    catch (Exception ex)
                    {
                        HandleException?.Invoke(ex);
                    }
                }
            }, TaskCreationOptions.LongRunning);
        }

19 Source : DataProvider.cs
with GNU Affero General Public License v3.0
from b11p

public async Task<(bool success, BindingInfo? result)> GetBindingInfoAsync(long qq)
        {
            try
            {
                var result = await _dbContext.Bindings.SingleOrDefaultAsync(b => b.UserId == qq).ConfigureAwait(false);
                return (true, result);
            }
            catch (Exception e)
            {
                OnException?.Invoke(e);
                return (false, default);
            }
        }

19 Source : BacktraceBase.cs
with MIT License
from backtrace-labs

public virtual void HandleApplicationThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            var exception = e.Exception as Exception;
            Send(new BacktraceReport(exception));
            OnUnhandledApplicationException?.Invoke(e.Exception);
        }

19 Source : BacktraceBase.cs
with MIT License
from backtrace-labs

private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            var exception = e.Exception as Exception;
            Send(new BacktraceReport(exception));
            OnUnhandledApplicationException?.Invoke(e.Exception);
        }

19 Source : BacktraceBase.cs
with MIT License
from backtrace-labs

private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var exception = e.ExceptionObject as Exception;
            Database?.Add(new BacktraceReport(exception), Attributes, MiniDumpType);
            OnUnhandledApplicationException?.Invoke(exception);
        }

19 Source : BacktraceApi.cs
with MIT License
from backtrace-labs

internal async Task<BacktraceResult> SendAsync(Guid requestId, string json, List<string> attachments, BacktraceReport report, int deduplication = 0)
        {
            string contentType = FormDataHelper.GetContentTypeWithBoundary(requestId);
            string boundary = FormDataHelper.GetBoundary(requestId);

            using (var content = new MultipartFormDataContent(boundary))
            {
                var requestUrl = _serverurl.ToString();
                if (deduplication > 0)
                {
                    requestUrl += $"&_mod_duplicate={deduplication}";
                }

                var request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
                content.AddJson("upload_file.json", json);
                content.AddFiles(attachments);

                //// clear and add content type with boundary tag
                content.Headers.Remove("Content-Type");
                content.Headers.TryAddWithoutValidation("Content-Type", contentType);
                request.Content = content;
                try
                {
                    using (var response = await HttpClient.SendAsync(request))
                    {
                        var fullResponse = await response.Content.ReadreplacedtringAsync();
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            var err = new WebException(response.ReasonPhrase);
                            System.Diagnostics.Trace.WriteLine(fullResponse);
                            OnServerError?.Invoke(err);
                            return BacktraceResult.OnError(report, err);
                        }
                        var result = JsonConvert.DeserializeObject<BacktraceResult>(fullResponse);
                        result.BacktraceReport = report;
                        OnServerResponse?.Invoke(result);
                        return result;
                    }
                }
                catch (Exception exception)
                {
                    System.Diagnostics.Trace.WriteLine($"Backtrace - Server error: {exception.ToString()}");
                    OnServerError?.Invoke(exception);
                    return BacktraceResult.OnError(report, exception);
                }
            }
        }

19 Source : Extensions.cs
with GNU General Public License v3.0
from BardMusicPlayer

public static async void SafeFireAndForget(this System.Threading.Tasks.Task task, bool continueOnCapturedContext = true, Action<Exception> onException = null)
#pragma warning restore RECS0165
        {
            try
            {
                await task.ConfigureAwait(continueOnCapturedContext);
            }
            catch (Exception ex) when (onException != null)
            {
                onException(ex);
            }
        }

19 Source : AlphaSynth.cs
with GNU General Public License v3.0
from BardMusicPlayer

private void OnSoundFontLoadFailed(Exception e)
        {
            var handler = SoundFontLoadFailed;
            if (handler != null)
            {
                handler(e);
            }
        }

19 Source : AlphaSynth.cs
with GNU General Public License v3.0
from BardMusicPlayer

private void OnMidiLoadFailed(Exception e)
        {
            var handler = MidiLoadFailed;
            if (handler != null)
            {
                handler(e);
            }
        }

19 Source : AlphaSynthWorkerApiBase.cs
with GNU General Public License v3.0
from BardMusicPlayer

protected virtual void OnSoundFontLoadFailed(Exception e)
        {
            DispatchOnUiThread(() => SoundFontLoadFailed?.Invoke(e));
        }

19 Source : AlphaSynthWorkerApiBase.cs
with GNU General Public License v3.0
from BardMusicPlayer

protected virtual void OnMidiLoadFailed(Exception e)
        {
            DispatchOnUiThread(() => MidiLoadFailed?.Invoke(e));
        }

19 Source : LottieFailureListener.cs
with Apache License 2.0
from Baseflow

public void OnResult(Java.Lang.Object p0)
        {
            var javaError = p0?.ToString();
            OnResultImpl?.Invoke(new Exception(javaError));
        }

19 Source : Enumerables.cs
with MIT License
from Bassman2

public static IEnumerable<T> CatchExceptions<T>(this IEnumerable<T> src, Action<Exception> action = null)
        {
            using (var enumerator = src.GetEnumerator())
            {
                bool next = true;
                while (next)
                {
                    try
                    {
                        next = enumerator.MoveNext();
                    }
                    catch (Exception ex)
                    {
                        if (action != null)
                        {
                            action(ex);
                        }
                        continue;
                    }

                    if (next)
                    {
                        yield return enumerator.Current;
                    }
                }
            }
        }

19 Source : Producer.cs
with MIT License
from BEagle1984

[SuppressMessage("", "VSTHRD103", Justification = "OK to call sync ProduceCore")]
        public void Produce(
            IOutboundEnvelope envelope,
            Action<IBrokerMessageIdentifier?> onSuccess,
            Action<Exception> onError)
        {
            try
            {
                AsyncHelper.RunSynchronously(
                    async () =>
                    {
                        await ExecutePipelineAsync(
                            new ProducerPipelineContext(envelope, this, _serviceProvider),
                            finalContext =>
                            {
                                ProduceCore(
                                    finalContext.Envelope.Message,
                                    finalContext.Envelope.RawMessage,
                                    finalContext.Envelope.Headers,
                                    finalContext.Envelope.ActualEndpointName,
                                    identifier =>
                                    {
                                        ((RawOutboundEnvelope)finalContext.Envelope).BrokerMessageIdentifier =
                                            identifier;
                                        _logger.LogProduced(envelope);
                                        onSuccess.Invoke(identifier);
                                    },
                                    exception =>
                                    {
                                        _logger.LogProduceError(envelope, exception);
                                        onError.Invoke(exception);
                                    });
                                _logger.LogProduced(envelope);

                                return Task.CompletedTask;
                            }).ConfigureAwait(false);
                    });
            }
            catch (Exception ex)
            {
                _logger.LogProduceError(envelope, ex);
                throw;
            }
        }

19 Source : Producer.cs
with MIT License
from BEagle1984

public void RawProduce(
            string actualEndpointName,
            byte[]? messageContent,
            IReadOnlyCollection<MessageHeader>? headers,
            Action<IBrokerMessageIdentifier?> onSuccess,
            Action<Exception> onError) =>
            ProduceCore(
                null,
                messageContent,
                headers,
                actualEndpointName,
                identifier =>
                {
                    _logger.LogProduced(Endpoint, actualEndpointName, headers, identifier);
                    onSuccess.Invoke(identifier);
                },
                exception =>
                {
                    _logger.LogProduceError(Endpoint, actualEndpointName, headers, exception);
                    onError.Invoke(exception);
                });

19 Source : Producer.cs
with MIT License
from BEagle1984

public void RawProduce(
            string actualEndpointName,
            Stream? messageStream,
            IReadOnlyCollection<MessageHeader>? headers,
            Action<IBrokerMessageIdentifier?> onSuccess,
            Action<Exception> onError) =>
            ProduceCore(
                null,
                messageStream,
                headers,
                actualEndpointName,
                identifier =>
                {
                    _logger.LogProduced(Endpoint, actualEndpointName, headers, identifier);
                    onSuccess.Invoke(identifier);
                },
                exception =>
                {
                    _logger.LogProduceError(Endpoint, actualEndpointName, headers, exception);
                    onError.Invoke(exception);
                });

19 Source : Producer.cs
with MIT License
from BEagle1984

public async Task ProduceAsync(
            IOutboundEnvelope envelope,
            Action<IBrokerMessageIdentifier?> onSuccess,
            Action<Exception> onError) =>
            await ExecutePipelineAsync(
                new ProducerPipelineContext(envelope, this, _serviceProvider),
                finalContext => ProduceCoreAsync(
                    finalContext.Envelope.Message,
                    finalContext.Envelope.RawMessage,
                    finalContext.Envelope.Headers,
                    finalContext.Envelope.ActualEndpointName,
                    identifier =>
                    {
                        ((RawOutboundEnvelope)finalContext.Envelope).BrokerMessageIdentifier = identifier;
                        _logger.LogProduced(envelope);
                        onSuccess.Invoke(identifier);
                    },
                    exception =>
                    {
                        _logger.LogProduceError(envelope, exception);
                        onError.Invoke(exception);
                    })).ConfigureAwait(false);

19 Source : Producer.cs
with MIT License
from BEagle1984

public Task RawProduceAsync(
            string actualEndpointName,
            byte[]? messageContent,
            IReadOnlyCollection<MessageHeader>? headers,
            Action<IBrokerMessageIdentifier?> onSuccess,
            Action<Exception> onError) =>
            ProduceCoreAsync(
                null,
                messageContent,
                headers,
                actualEndpointName,
                identifier =>
                {
                    _logger.LogProduced(Endpoint, actualEndpointName, headers, identifier);
                    onSuccess.Invoke(identifier);
                },
                exception =>
                {
                    _logger.LogProduceError(Endpoint, actualEndpointName, headers, exception);
                    onError.Invoke(exception);
                });

19 Source : Producer.cs
with MIT License
from BEagle1984

public Task RawProduceAsync(
            string actualEndpointName,
            Stream? messageStream,
            IReadOnlyCollection<MessageHeader>? headers,
            Action<IBrokerMessageIdentifier?> onSuccess,
            Action<Exception> onError) =>
            ProduceCoreAsync(
                null,
                messageStream,
                headers,
                actualEndpointName,
                identifier =>
                {
                    _logger.LogProduced(Endpoint, actualEndpointName, headers, identifier);
                    onSuccess.Invoke(identifier);
                },
                exception =>
                {
                    _logger.LogProduceError(Endpoint, actualEndpointName, headers, exception);
                    onError.Invoke(exception);
                });

19 Source : RabbitProducer.cs
with MIT License
from BEagle1984

[SuppressMessage("", "VSTHRD110", Justification = "Result observed via ContinueWith")]
        protected override void ProduceCore(
            object? message,
            byte[]? messageBytes,
            IReadOnlyCollection<MessageHeader>? headers,
            string actualEndpointName,
            Action<IBrokerMessageIdentifier?> onSuccess,
            Action<Exception> onError)
        {
            var queuedMessage = new QueuedMessage(messageBytes, headers, actualEndpointName);

            AsyncHelper.RunValueTaskSynchronously(() => _queueChannel.Writer.WriteAsync(queuedMessage));

            queuedMessage.TaskCompletionSource.Task.ContinueWith(
                task =>
                {
                    if (task.IsCompletedSuccessfully)
                        onSuccess.Invoke(task.Result);
                    else
                        onError.Invoke(task.Exception);
                },
                TaskScheduler.Default);
        }

19 Source : RabbitProducer.cs
with MIT License
from BEagle1984

protected override async Task ProduceCoreAsync(
            object? message,
            byte[]? messageBytes,
            IReadOnlyCollection<MessageHeader>? headers,
            string actualEndpointName,
            Action<IBrokerMessageIdentifier?> onSuccess,
            Action<Exception> onError)
        {
            var queuedMessage = new QueuedMessage(messageBytes, headers, actualEndpointName);

            await _queueChannel.Writer.WriteAsync(queuedMessage).ConfigureAwait(false);

            queuedMessage.TaskCompletionSource.Task.ContinueWith(
                    task =>
                    {
                        if (task.IsCompletedSuccessfully)
                            onSuccess.Invoke(task.Result);
                        else
                            onError.Invoke(task.Exception);
                    },
                    TaskScheduler.Default)
                .FireAndForget();
        }

19 Source : KafkaProducer.cs
with MIT License
from BEagle1984

[SuppressMessage("", "CA1031", Justification = "Exception forwarded")]
        protected override void ProduceCore(
            object? message,
            byte[]? messageBytes,
            IReadOnlyCollection<MessageHeader>? headers,
            string actualEndpointName,
            Action<IBrokerMessageIdentifier?> onSuccess,
            Action<Exception> onError)
        {
            Check.NotNull(onSuccess, nameof(onSuccess));
            Check.NotNull(onError, nameof(onError));

            var kafkaMessage = new Message<byte[]?, byte[]?>
            {
                Key = GetKafkaKey(headers),
                Value = messageBytes
            };

            if (headers != null && headers.Count >= 1)
                kafkaMessage.Headers = headers.ToConfluentHeaders();

            var topicParreplacedion = new TopicParreplacedion(
                actualEndpointName,
                GetParreplacedion(headers));

            GetConfluentProducer().Produce(
                topicParreplacedion,
                kafkaMessage,
                deliveryReport =>
                {
                    try
                    {
                        if (deliveryReport.Error != null && deliveryReport.Error.IsError)
                        {
                            // Disposing and re-creating the producer will maybe fix the issue
                            if (Endpoint.Configuration.DisposeOnException)
                                DisposeConfluentProducer();

                            throw new ProduceException(
                                $"Error occurred producing the message. (error code {deliveryReport.Error.Code})");
                        }

                        if (Endpoint.Configuration.ArePersistenceStatusReportsEnabled)
                            CheckPersistenceStatus(deliveryReport);

                        onSuccess.Invoke(
                            new KafkaOffset(deliveryReport.TopicParreplacedionOffsetError.TopicParreplacedionOffset));
                    }
                    catch (Exception ex)
                    {
                        onError.Invoke(ex);
                    }
                });
        }

19 Source : TcpMapService.cs
with MIT License
from BlazorPlus

static public void OnError(Exception err)
		{
			Console.WriteLine(err);
			ServiceError = err;
			ServiceErrors.Enqueue(err);
			while (ServiceErrors.Count > 100)
				ServiceErrors.TryDequeue(out _);
			ErrorOccurred?.Invoke(err);
		}

19 Source : ForeverTransport.cs
with GNU General Public License v3.0
from bonarr

public void Complete(Exception error)
            {
                _lifetime.Complete(error);

                _transport.Dispose();

                if (_transport.AfterRequestEnd != null)
                {
                    _transport.AfterRequestEnd(error);
                }
            }

19 Source : Ext.cs
with MIT License
from bonzaiferroni

internal static void ReadBytesAsync (
      this Stream stream, int length, Action<byte []> completed, Action<Exception> error)
    {
      var buffer = new byte [length];
      stream.BeginRead (
        buffer,
        0,
        length,
        ar => {
          try {
            var len = stream.EndRead (ar);
            var bytes = len < 1
                      ? new byte [0]
                      : len < length
                        ? stream.readBytes (buffer, len, length - len)
                        : buffer;

            if (completed != null)
              completed (bytes);
          }
          catch (Exception ex) {
            if (error != null)
              error (ex);
          }
        },
        null);
    }

19 Source : SocketWrapper.cs
with GNU General Public License v3.0
from bp2008

public Task<int> Receive(byte[] buffer, Action<int> callback, Action<Exception> error, int offset)
        {
            try
            {
                Func<AsyncCallback, object, IAsyncResult> begin =
               (cb, s) => _stream.BeginRead(buffer, offset, buffer.Length, cb, s);

                Task<int> task = Task.Factory.FromAsync<int>(begin, _stream.EndRead, null);
                task.ContinueWith(t => callback(t.Result), TaskContinuationOptions.NotOnFaulted)
                    .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
                task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
                return task;
            }
            catch (Exception e)
            {
                error(e);
                return null;
            }
        }

19 Source : WebSocketConnection.cs
with GNU General Public License v3.0
from bp2008

private void HandleReadError(Exception e)
    {
      if (e is AggregateException) {
        var agg = e as AggregateException;
        HandleReadError(agg.InnerException);
        return;
      }

      if (e is ObjectDisposedException) {
        FleckLog.Debug("Swallowing ObjectDisposedException", e);
        return;
      }

      OnError(e);
            
      if (e is HandshakeException) {
        FleckLog.Debug("Error while reading", e);
      } else if (e is WebSocketException) {
        FleckLog.Debug("Error while reading", e);
        Close(((WebSocketException)e).StatusCode);
      } else if (e is SubProtocolNegotiationFailureException) {
        FleckLog.Debug(e.Message);
        Close(WebSocketStatusCodes.ProtocolError);
      } else if (e is IOException) {
        FleckLog.Debug("Error while reading", e);
        Close(WebSocketStatusCodes.AbnormalClosure);
      } else {
        FleckLog.Error("Application Error", e);
        Close(WebSocketStatusCodes.InternalServerError);
      }
    }

19 Source : SocketWrapper.cs
with GNU General Public License v3.0
from bp2008

public Task Authenticate(X509Certificate2 certificate, Action callback, Action<Exception> error)
        {
            var ssl = new SslStream(_stream, false);
            _stream = ssl;
            Func<AsyncCallback, object, IAsyncResult> begin =
                (cb, s) => ssl.BeginAuthenticatereplacederver(certificate, false, SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls, false, cb, s);
                
            Task task = Task.Factory.FromAsync(begin, ssl.EndAuthenticatereplacederver, null);
            task.ContinueWith(t => callback(), TaskContinuationOptions.NotOnFaulted)
                .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
            task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);

            return task;
        }

19 Source : SocketWrapper.cs
with GNU General Public License v3.0
from bp2008

public Task<ISocket> Accept(Action<ISocket> callback, Action<Exception> error)
        {
            Func<IAsyncResult, ISocket> end = r => {
                _tokenSource.Token.ThrowIfCancellationRequested();
                return new SocketWrapper(_socket.EndAccept(r));
            };
            var task = _taskFactory.FromAsync(_socket.BeginAccept, end, null);
            task.ContinueWith(t => callback(t.Result), TaskContinuationOptions.OnlyOnRanToCompletion)
                .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
            task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
            return task;
        }

19 Source : SocketWrapper.cs
with GNU General Public License v3.0
from bp2008

public Task Send(byte[] buffer, Action callback, Action<Exception> error)
        {
            if (_tokenSource.IsCancellationRequested)
                return null;

            try
            {
                Func<AsyncCallback, object, IAsyncResult> begin =
                    (cb, s) => _stream.BeginWrite(buffer, 0, buffer.Length, cb, s);

                Task task = Task.Factory.FromAsync(begin, _stream.EndWrite, null);
                task.ContinueWith(t => callback(), TaskContinuationOptions.NotOnFaulted)
                    .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
                task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);

                return task;
            }
            catch (Exception e)
            {
                error(e);
                return null;
            }
        }

19 Source : MicroCoroutine.cs
with GNU General Public License v3.0
from BramDC3

public void Run()
        {
            lock (runningAndQueueLock)
            {
                running = true;
            }

            lock (arrayLock)
            {
                var j = tail - 1;

                // eliminate array-bound check for i
                for (int i = 0; i < coroutines.Length; i++)
                {
                    var coroutine = coroutines[i];
                    if (coroutine != null)
                    {
                        try
                        {
                            if (!coroutine.MoveNext())
                            {
                                coroutines[i] = null;
                            }
                            else
                            {
#if UNITY_EDITOR
                                // validation only on Editor.
                                if (coroutine.Current != null)
                                {
                                    UnityEngine.Debug.LogWarning("MicroCoroutine supports only yield return null. return value = " + coroutine.Current);
                                }
#endif

                                continue; // next i 
                            }
                        }
                        catch (Exception ex)
                        {
                            coroutines[i] = null;
                            try
                            {
                                unhandledExceptionCallback(ex);
                            }
                            catch { }
                        }
                    }

                    // find null, loop from tail
                    while (i < j)
                    {
                        var fromTail = coroutines[j];
                        if (fromTail != null)
                        {
                            try
                            {
                                if (!fromTail.MoveNext())
                                {
                                    coroutines[j] = null;
                                    j--;
                                    continue; // next j
                                }
                                else
                                {
#if UNITY_EDITOR
                                    // validation only on Editor.
                                    if (fromTail.Current != null)
                                    {
                                        UnityEngine.Debug.LogWarning("MicroCoroutine supports only yield return null. return value = " + coroutine.Current);
                                    }
#endif

                                    // swap
                                    coroutines[i] = fromTail;
                                    coroutines[j] = null;
                                    j--;
                                    goto NEXT_LOOP; // next i
                                }
                            }
                            catch (Exception ex)
                            {
                                coroutines[j] = null;
                                j--;
                                try
                                {
                                    unhandledExceptionCallback(ex);
                                }
                                catch { }
                                continue; // next j
                            }
                        }
                        else
                        {
                            j--;
                        }
                    }

                    tail = i; // loop end
                    break; // LOOP END

                    NEXT_LOOP:
                    continue;
                }


                lock (runningAndQueueLock)
                {
                    running = false;
                    while (waitQueue.Count != 0)
                    {
                        if (coroutines.Length == tail)
                        {
                            Array.Resize(ref coroutines, checked(tail * 2));
                        }
                        coroutines[tail++] = waitQueue.Dequeue();
                    }
                }
            }
        }

19 Source : Do.cs
with GNU General Public License v3.0
from BramDC3

public override void OnError(Exception error)
            {
                try
                {
                    parent.onError(error);
                }
                catch (Exception ex)
                {
                    try { observer.OnError(ex); } finally { Dispose(); };
                    return;
                }
                try { observer.OnError(error); } finally { Dispose(); };
            }

19 Source : Do.cs
with GNU General Public License v3.0
from BramDC3

public override void OnError(Exception error)
            {
                try
                {
                    parent.onError(error);
                }
                catch (Exception ex)
                {
                    try { observer.OnError(ex); }
                    finally { Dispose(); }
                    return;
                }


                try { observer.OnError(error); }
                finally { Dispose(); }
            }

19 Source : ThreadSafeQueueWorker.cs
with GNU General Public License v3.0
from BramDC3

public void ExecuteAll(Action<Exception> unhandledExceptionCallback)
        {
            lock (gate)
            {
                if (actionListCount == 0) return;

                dequing = true;
            }

            for (int i = 0; i < actionListCount; i++)
            {
                var action = actionList[i];
                var state = actionStates[i];
                try
                {
                    action(state);
                }
                catch (Exception ex)
                {
                    unhandledExceptionCallback(ex);
                }
                finally
                {
                    // Clear
                    actionList[i] = null;
                    actionStates[i] = null;
                }
            }

            lock (gate)
            {
                dequing = false;

                var swapTempActionList = actionList;
                var swapTempActionStates = actionStates;

                actionListCount = waitingListCount;
                actionList = waitingList;
                actionStates = waitingStates;

                waitingListCount = 0;
                waitingList = swapTempActionList;
                waitingStates = swapTempActionStates;
            }
        }

19 Source : MainThreadDispatcher.cs
with GNU General Public License v3.0
from BramDC3

public static void Send(Action<object> action, object state)
        {
#if UNITY_EDITOR
            if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.Enqueue(action, state); return; }
#endif

            if (mainThreadToken != null)
            {
                try
                {
                    action(state);
                }
                catch (Exception ex)
                {
                    var dispatcher = MainThreadDispatcher.Instance;
                    if (dispatcher != null)
                    {
                        dispatcher.unhandledExceptionCallback(ex);
                    }
                }
            }
            else
            {
                Post(action, state);
            }
        }

19 Source : MainThreadDispatcher.cs
with GNU General Public License v3.0
from BramDC3

public static void UnsafeSend(Action action)
        {
#if UNITY_EDITOR
            if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.UnsafeInvoke(action); return; }
#endif

            try
            {
                action();
            }
            catch (Exception ex)
            {
                var dispatcher = MainThreadDispatcher.Instance;
                if (dispatcher != null)
                {
                    dispatcher.unhandledExceptionCallback(ex);
                }
            }
        }

19 Source : MainThreadDispatcher.cs
with GNU General Public License v3.0
from BramDC3

public static void UnsafeSend<T>(Action<T> action, T state)
        {
#if UNITY_EDITOR
            if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.UnsafeInvoke(action, state); return; }
#endif

            try
            {
                action(state);
            }
            catch (Exception ex)
            {
                var dispatcher = MainThreadDispatcher.Instance;
                if (dispatcher != null)
                {
                    dispatcher.unhandledExceptionCallback(ex);
                }
            }
        }

19 Source : MainThreadDispatcher.cs
with GNU General Public License v3.0
from BramDC3

void Awake()
        {
            if (instance == null)
            {
                instance = this;
                mainThreadToken = new object();
                initialized = true;

                updateMicroCoroutine = new MicroCoroutine(ex => unhandledExceptionCallback(ex));
                fixedUpdateMicroCoroutine = new MicroCoroutine(ex => unhandledExceptionCallback(ex));
                endOfFrameMicroCoroutine = new MicroCoroutine(ex => unhandledExceptionCallback(ex));

                StartCoroutine(RunUpdateMicroCoroutine());
                StartCoroutine(RunFixedUpdateMicroCoroutine());
                StartCoroutine(RunEndOfFrameMicroCoroutine());

                DontDestroyOnLoad(gameObject);
            }
            else
            {
                if (this != instance)
                {
                    if (cullingMode == CullingMode.Self)
                    {
                        // Try to destroy this dispatcher if there's already one in the scene.
                        Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Removing myself...");
                        DestroyDispatcher(this);
                    }
                    else if (cullingMode == CullingMode.All)
                    {
                        Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Cleaning up all excess dispatchers...");
                        CullAllExcessDispatchers();
                    }
                    else
                    {
                        Debug.LogWarning("There is already a MainThreadDispatcher in the scene.");
                    }
                }
            }
        }

19 Source : Observable.Unity.cs
with GNU General Public License v3.0
from BramDC3

public static IEnumerator ToAwaitableEnumerator<T>(this IObservable<T> source, Action<T> onResult, Action<Exception> onError, CancellationToken cancel = default(CancellationToken))
        {
            var enumerator = new ObservableYieldInstruction<T>(source, false, cancel);
            var e = (IEnumerator<T>)enumerator;
            while (e.MoveNext() && !cancel.IsCancellationRequested)
            {
                yield return null;
            }

            if (cancel.IsCancellationRequested)
            {
                enumerator.Dispose();
                yield break;
            }

            if (enumerator.HasResult)
            {
                onResult(enumerator.Result);
            }
            else if (enumerator.HasError)
            {
                onError(enumerator.Error);
            }
        }

19 Source : Notification.cs
with GNU General Public License v3.0
from BramDC3

public override void Accept(Action<T> onNext, Action<Exception> onError, Action onCompleted)
            {
                if (onNext == null)
                    throw new ArgumentNullException("onNext");
                if (onError == null)
                    throw new ArgumentNullException("onError");
                if (onCompleted == null)
                    throw new ArgumentNullException("onCompleted");

                onError(Exception);
            }

See More Examples