System aggregateexception произошла одна или несколько ошибок

I’m trying to call LoadPickerData method to load the result in a Picker using async/await from the a ViewModel. I get the following error:
enter image description here

Error

System.AggregateException
  Message=One or more errors occurred. (A task was canceled.)
  Source=mscorlib
  StackTrace:
  at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2027 
  at System.Threading.Tasks.Task`1[TResult].GetResultCore (System.Boolean waitCompletionNotification) [0x0002b] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs:496 
  at System.Threading.Tasks.Task`1[TResult].get_Result () [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs:466 
  at EmployeeApp.Helpers.ConnectivityHelper.CheckConnectivity () [0x00049] in F:WorkspaceBajaDevMPA_ProjectEmployeeAppHelpersConnectivityHelper.cs:34 
  at EmployeeApp.Helpers.ConnectivityHelper.get_IsConnected () [0x00000] in F:WorkspaceBajaDevMPA_ProjectEmployeeAppHelpersConnectivityHelper.cs:21 
  at EmployeeApp.ViewModels.BaseViewModel.get_ServiceAreaStore () [0x00000] in F:WorkspaceBajaDevMPA_ProjectEmployeeAppViewModelsBaseViewModel.cs:27 
  at EmployeeApp.ViewModels.MailboxViewModel.GetPickerServiceArea () [0x0000f] in F:WorkspaceBajaDevMPA_ProjectEmployeeAppViewModelsMailboxViewModel.cs:60 
  at EmployeeApp.MailboxPage.LoadPickerData () [0x0002b] in F:WorkspaceBajaDevMPA_ProjectEmployeeAppViewsMailBoxPage.xaml.cs:70 
  at EmployeeApp.MailboxPage.OnAppearing () [0x0002c] in F:WorkspaceBajaDevMPA_ProjectEmployeeAppViewsMailBoxPage.xaml.cs:31 
  at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1021 
  at Android.App.SyncContext+<>c__DisplayClass2_0.<Post>b__0 () [0x00000] in <06692e0cad5848598a0f46942a89e99f>:0 
  at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in <06692e0cad5848598a0f46942a89e99f>:0 
  at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in <06692e0cad5848598a0f46942a89e99f>:0 
  at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.44(intptr,intptr)

I’m trying to load the result of a GET request in a picker, but when I start the app the first time, it does not and I get the previous exception and the second time I run it I no longer get that error.
I looked for why and I was making the call of an asynchronous method in a constructor and that is bad code, I changed it to an OnAppearing () method but still that exception keeps coming out and I don’t have idea the why yet

MailboxPage.xaml.cs

public MailboxPage()
    {
        InitializeComponent();

        BindingContext = viewModel = new MailboxViewModel();
    }

    protected override async void OnAppearing()
    {
        base.OnAppearing();
        await LoadPickerData();
    }

private async Task<IEnumerable<ServiceArea>> LoadPickerData()
    {
        var vm = new MailboxViewModel();

        var servicesareas = await vm.GetPickerServiceArea();
        try
        {
            ServiceAreaPicker.ItemsSource = servicesareas.ToList();
            ServiceAreaPicker.ItemDisplayBinding = new Binding("Name");
        }
        catch(AggregateException ae)
        {
            foreach (var e in ae.Flatten().InnerExceptions)
            {
                Debug.WriteLine($"{e.GetType().FullName} { e.Message}");
            }
        }

        return servicesareas;
    }

MailboxViewModel.cs

public async Task<IEnumerable<ServiceArea>> GetPickerServiceArea()
    {
        try
        {
            PickerItems = await ServiceAreaStore.GetPickerItemsAsync(true);
            foreach (var item in PickerItems)
                Items.Add(item);
        }
        catch (AggregateException ae)
        {
            foreach (var e in ae.Flatten().InnerExceptions)
            {
                Debug.WriteLine($"{e.GetType().FullName} { e.Message}");
            }
        }

        return PickerItems;
    }

ServiceAreaStoreAPI.cs

public async Task<IEnumerable<ServiceArea>> GetPickerItemsAsync(bool forceRefresh = false)
    {
        if (forceRefresh)
        {
            var json = await Client.GetStringAsync($"api/servicearea");
            Servicesareas = await Task.Run(() => JsonConvert.DeserializeObject<IEnumerable<ServiceArea>>(json));
            try
            {
                var success = LocalDatabase.AddItemsAsync(Servicesareas);
                if (!success.Result)
                {
                    //Log de fallo en la insercion de datos.
                }
            }
            catch(AggregateException ae)
            {
               foreach (var e in ae.Flatten().InnerExceptions)
               {
                  Debug.WriteLine($"{e.GetType().FullName} { e.Message}");
               }
            }
        }
        return Servicesareas;
    }

  • Remove From My Forums

 none

Ошибка при публикации проекта.

  • Вопрос

  • Здравствуйте. При публикации проекта ASP.NET MVC5 я получаю ошибку «Сбой публикации»

    Содержимое файла tmpD547.tmp:

    16.03.2018 9:46:35
    System.AggregateException: Произошла одна или несколько ошибок. ---> System.Exception: Сбой публикации из-за ошибок сборки. Дополнительную информацию см. в списке ошибок.
       --- Конец трассировки внутреннего стека исключений ---
       в System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
       в System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
       в Microsoft.VisualStudio.Web.Publish.PublishService.VsWebProjectPublish.<>c__DisplayClass40_0.<PublishAsync>b__2()
       в System.Threading.Tasks.Task`1.InnerInvoke()
       в System.Threading.Tasks.Task.Execute()
    --- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
       в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       в Microsoft.VisualStudio.ApplicationCapabilities.Publish.ViewModel.ProfileSelectorViewModel.<RunPublishTaskAsync>d__88.MoveNext()
    ---> (Внутреннее исключение #0) System.Exception: Сбой публикации из-за ошибок сборки. Дополнительную информацию см. в списке ошибок.<---
    
    ===================

    Версия студии 15.6.2. Подскажите пожалуйста, в чём может быть проблема?

Ответы

  • Проблему нашёл. В проект попал файл Thumbs.db. 

    • Помечено в качестве ответа

      16 марта 2018 г. 8:02

We are here once again to help you debug common .NET exceptions. This time I want to help you debug the rather generic System.AggregateException. As the name implies, AggregateException is used to batch one or more exceptions together in a single exception. In this post, I’ll show you why this exception occurs and how to debug it in your C# code.

Debugging System.AggregateException - even in async code

Causing and handling the error

Let’s start by forcing a new AggregateException. The exception is used heavily in .NET’s Task libraries, why choosing an example involving tasks is a no-brainer:

Task task1 = Task.Factory.StartNew(() => { throw new ArgumentException(); } );
Task task2 = Task.Factory.StartNew(() => { throw new UnauthorizedAccessException(); } );

try
{
    Task.WaitAll(task1, task2);
}
catch (AggregateException ae)
{
}

In the example above, we spin up two tasks, each throwing an exception. By calling WaitAll we tell .NET to invoke and wait for a result from each of the two tasks. The combined result of the two tasks will be an AggregateException.

You’ve probably come to this article because of one of the following error messages:

  • System.AggregateException: One or more errors occurred.
  • A task was canceled
  • ‘System.AggregateException’ occurred in mscorlib.dll

In the following section, I will show you how to debug and fix each.

Debugging the error

When inspecting the exception from the previous example in the debugger, we see the two thrown exceptions in the InnerExceptions property:

Inner exceptions

Just as promised in the name, AggregateException is a wrapper of other exceptions. In the example, both the ArgumentException and the UnauthorizedAccessException is available as inner exceptions.

In some scenarios you would add a catch blog per exception like this:

try
{
    ...
}
catch (ArgumentException ex1)
{
    // Log and re-throw
}
catch (UnauthorizedAccessException ex2)
{
    // Log and swallow
}

This way, you can generate individual error messages to the user, log the exception but only re-throw one of them, or something third. Rather than looping over each exception in the InnerExceptions property, AggregateException provides a handy little helper method named Handle:

try
{
    ...
}
catch (AggregateException ae)
{
    ae.Handle(inner =>
    {
        // Log inner
        ...
        return inner is UnauthorizedAccessException;
    });
}

In the example, the Handle method logs each exception. The func needs to return a bool indicating if each exception has been handled. In this case, we tell the Handle method that the UnauthorizedAccessException is handled, but not the ArgumentException. This will cause the AggregateException to be thrown back to the calling code, but without the UnauthorizedAccessException in the InnerExceptions property (because we marked that exception as already handled).

AggregateExceptions from HttpClient

When dealing with the System.Net.Http.HttpClient class, you may experience the AggregateException. This is mostly when implementing async code using the old API (Wait, ContinueWith, etc.). Let’s look at an example:

try
{
    var client = new HttpClient();
    var task = client.GetStringAsync("https://httpstat.us/500");
    task.Wait();
    var result = task.Result;
}
catch (AggregateException ex)
{
    throw ex;
}

The request to https://httpstat.us/500 returns an HTTP status code of 500 which throws a HttpRequestException. I’m using the GetStringAsync method as an example, but the code would look similar if using other async messages like PostAsync. As we saw previously, exceptions from the tasks API are wrapped in an AggregateException, containing the HTTP exception in the InnerExceptions property.

To get the actual exception, you have a range of options. I’ll re-use the need for logging the exception to illustrate. Let’s start with the Handle method I showed you in a previous example:

try
{
    ...
}
catch (AggregateException ex)
{
    ex.Handle(inner =>
    {
        if (inner is HttpRequestException)
        {
            // Log the exception
            
            return true;
        }
        
        return false;
    });
}

I’m checking if the inner exception is of type HttpRequestException and in that case tell the Handle method that this exception has been handled. In any other scenario, I tell Handle to re-throw the original exception (by returning false).

Another approach will be to use the ContinueWith method to catch and handle the AggregateException:

var client = new HttpClient();
var task = client
    .GetStringAsync("https://httpstat.us/500")
    .ContinueWith(t =>
    {
        try
        {
            return t.Result;
        }
        catch (AggregateException ex)
        {
            ex.Handle(inner =>
            {
                if (inner is HttpRequestException)
                {
                    // Log the exception

                    return true;
                }

                return false;
            });
        }
        catch (Exception ex)
        {
            throw ex;
        }

        return null;
    });
task.Wait();
var result = task.Result;

I’ve basically just moved the try/catch from before inside the ContinueWith method.

Finally, if you are on .NET 4.5 (you probably are and if not, you should be) you can use the await keyword:

var client = new HttpClient();
try
{
    var result = await client.GetStringAsync("https://httpstat.us/500");
}
catch (HttpRequestException ex)
{
    // Log the exception
}
catch (Exception ex)
{
    throw ex;
}

Notice how the code catches HttpRequestException instead of AggregateException. This is because .NET automatically unwraps the AggregateException and throws the underlying exception instead. This is what you want in most cases. Yet another benefit of porting existing async code to use the await keyword.

Also make sure to read the other posts in this series: Debugging common .NET exception.

elmah.io: Error logging and Uptime Monitoring for your web apps

This blog post is brought to you by elmah.io. elmah.io is error logging, uptime monitoring, deployment tracking, and service heartbeats for your .NET and JavaScript applications. Stop relying on your users to notify you when something is wrong or dig through hundreds of megabytes of log files spread across servers. With elmah.io, we store all of your log messages, notify you through popular channels like email, Slack, and Microsoft Teams, and help you fix errors fast.

elmah.io app banner

See how we can help you monitor your website for crashes
Monitor your website

  • Remove From My Forums
  • Question

  • From @riverokellerman via Twitter:

    We are getting strange errors with our systems in productions, related to documentDB.

    The errors we are getting are:

    System.AggregateException: One or more errors occurred. —> System.InvalidOperationException: The request message was already sent. Cannot send the same request message multiple times.
       at
    System.Net.Http.HttpClient.CheckRequestMessage(HttpRequestMessage request)
       at
    System.Net.Http.HttpClient.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
       at
    Microsoft.Azure.Documents.Client.GatewayProxy.<>c__DisplayClass1f.<<InvokeAsync>b__1e>d__21.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.BackoffRetryUtility`1.<>c__DisplayClass2.<<ExecuteAsync>b__1>d__4.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.BackoffRetryUtility`1.<ExecuteRetry>d__16.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.BackoffRetryUtility`1.<ExecuteAsync>d__7.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.Client.GatewayProxy.<InvokeAsync>d__2c.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.Client.GatewayProxy.<ReadFeedAsync>d__1a.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.Client.DocumentClient.<ExecuteQueryAsync>d__2cb.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
       at
    Microsoft.Azure.Documents.Linq.DocumentQueryExecutionContext.<ExecuteOnceAsync>d__c.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.BackoffRetryUtility`1.<>c__DisplayClass2.<<ExecuteAsync>b__1>d__4.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.BackoffRetryUtility`1.<ExecuteRetry>d__16.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.BackoffRetryUtility`1.<ExecuteAsync>d__7.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.Linq.DocumentQuery`1.<ExecuteNextPrivateAsync>d__3`1.MoveNext()
       — End of inner exception stack trace —
       at System.Threading.Tasks.Task.WaitAll(Task[] tasks, Int32 millisecondsTimeout, CancellationToken cancellationToken)
       at System.Threading.Tasks.Task.WaitAll(Task[] tasks, Int32 millisecondsTimeout)
       at System.Threading.Tasks.Task.WaitAll(Task[] tasks)                                

    Here is another one: System.AggregateException: One or more errors occurred. —>

    System.Net.Http.HttpRequestException: An error occurred while sending the request. —>

    System.Net.WebException: Unable to connect to the remote server —>

    System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed
    to respond 191.237.32.44:443
       at
    System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
       at
    System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
       — End of inner exception stack trace —
       at
    System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
       at
    System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
       — End of inner exception stack trace —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.Client.GatewayServiceConfigurationReader.<InitializeAsync>d__0.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.Client.DocumentClient.<DeduceConsistencyLevelAsync>d__2e2.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.Client.DocumentClient.<GetInitializationTask>d__1b.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.Client.DocumentClient.<EnsureValidClientAsync>d__20.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.Client.DocumentClient.<ExecuteQueryAsync>d__2cb.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
       at
    Microsoft.Azure.Documents.Linq.DocumentQueryExecutionContext.<ExecuteOnceAsync>d__c.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.BackoffRetryUtility`1.<>c__DisplayClass2.<<ExecuteAsync>b__1>d__4.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.BackoffRetryUtility`1.<ExecuteRetry>d__16.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.BackoffRetryUtility`1.<ExecuteAsync>d__7.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.Linq.DocumentQueryExecutionContext.<ExecuteAllAsync>d__7.MoveNext()
    — End of stack trace from previous location where exception was thrown —
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at
    Microsoft.Azure.Documents.Linq.DocumentQuery`1.<GetEnumeratorTAsync>d__10.MoveNext()
       — End of inner exception stack trace —
       at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
       at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
       at System.Threading.Tasks.Task`1.get_Result()
       at
    Microsoft.Azure.Documents.Linq.DocumentQuery`1.GetEnumerator()
       at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
       at Leadbox.DataAccess.CustomerRepository.ReadByLeadId(Guid id) in

    Thanks!

    @AzureSupport

    • Edited by

      Tuesday, March 22, 2016 5:49 PM

Answers

  • This was fixed in 1.5.2 of the .NET SDK for DocumentDB. Please update your SDK.

    • Proposed as answer by
      Ryan CrawCour [MSFT]
      Tuesday, March 29, 2016 8:28 PM
    • Marked as answer by
      Han, MSFT
      Friday, September 30, 2016 10:47 PM

Обработка ошибок и отмена операции

Последнее обновление: 15.02.2022

При выполнении параллельных операций также могут возникать ошибки, обработка которых имеет свои особенности. При параллельной обработке коллекция
разделяется а части, и каждая часть обрабатывается в отдельном потоке. Однако если возникнет ошибка в одном из потоков, то система прерывает выполнение всех потоков.

При генерации исключений все они агрегируются в одном исключении типа AggregateException

Например, пусть в метод факториала передается массив объектов, который содержит не только числа, но и строки:

object[] numbers = new object[] { 1, 2, 3, 4, 5, "6" };

var squares = from n in numbers.AsParallel()
                 let x = (int)n
                 select Square(x);
try
{
    squares.ForAll(n => Console.WriteLine(n));
}
catch (AggregateException ex)
{
    foreach (var e in ex.InnerExceptions)
    {
        Console.WriteLine(e.Message);
    }
}

int Square(int n) => n * n;

Запустим проект без отладки. И так как массив содержит строку, то попытка приведения закончится неудачей, и на консоль будет выведено сообщение об ошибке.
При запуске приложения в Visual Studio в режиме отладки выполнение остановится на строке преобразования.
А после продолжения также сработает перехват исключения в блоке catch, и на консоль будет выведено сообщение об ошибке.

Прерывание параллельной операции

Вполне вероятно, что нам может потребоваться прекратить операцию до ее завершения. В этом случае мы можем использовать метод WithCancellation(),
которому в качестве параметра передается токен CancellationToken:

CancellationTokenSource cts = new CancellationTokenSource();
// запускаем дополнительную задачу, в которой через 400 миллисек. прерываем операцию
new Task(() =>
{
    Thread.Sleep(400);
    cts.Cancel();
}).Start();

try
{
    int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, };

    var squares = from n in numbers.AsParallel().WithCancellation(cts.Token)
                     select Square(n);

    foreach (var n in squares)
        Console.WriteLine(n);
}
catch (OperationCanceledException)
{
    Console.WriteLine("Операция была прервана");
}
catch (AggregateException ex)
{
    if (ex.InnerExceptions != null)
    {
        foreach (Exception e in ex.InnerExceptions)
            Console.WriteLine(e.Message);
    }
}
finally
{
    cts.Dispose();
}
int Square(int n)
{
    var result = n * n;
    Console.WriteLine($"Квадрат числа {n} равен {result}");
    Thread.Sleep(1000); // имитация долгого вычисления
    return result;
}

В параллельной запущенной задаче вызывается метод cts.Cancel(), что приводит к завершению операции и генерации исключения OperationCanceledException:

Квадрат числа 5 равен 25
Квадрат числа 3 равен 9
Квадрат числа 1 равен 1
Квадрат числа 7 равен 49
Операция была прервана

При этом также имеет смысл обрабатывать исключение AggregateException, так как если параллельно возникает еще одно исключение, то это исключение,
а также OperationCanceledException помещаются внутрь одного объекта AggregateException.

3 / 3 / 1

Регистрация: 09.08.2020

Сообщений: 46

1

VS 2019

Ошибка при публикации

22.09.2021, 17:44. Показов 7040. Ответов 7


Уважаемые пользователи, почему возникает данная ошибка? Не могу опубликовать проект.

Ошибка при публикации

Ошибка при публикации

В файле «tmp4D94»:
22.09.2021 17:05:44
System.AggregateException: Произошла одна или несколько ошибок. —> Microsoft.WebTools.Shared.Exceptions.WebToolsExcep tion: При публикации произошла ошибка. Не удалось определить причину ошибки. Дополнительные сведения см. в журнале вывода.
— Конец трассировки внутреннего стека исключений —
—> (Внутреннее исключение #0) Microsoft.WebTools.Shared.Exceptions.WebToolsExcep tion: При публикации произошла ошибка. Не удалось определить причину ошибки. Дополнительные сведения см. в журнале вывода. <—

Microsoft.WebTools.Shared.Exceptions.WebToolsExcep tion: При публикации произошла ошибка. Не удалось определить причину ошибки. Дополнительные сведения см. в журнале вывода.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

1728 / 1665 / 360

Регистрация: 17.02.2019

Сообщений: 2,645

22.09.2021, 18:14

2

А что пишут в Диагностический журнал записан сюда: "C:UsersAdminAppDataLocalTemptmp4D94.tmp".

0

3 / 3 / 1

Регистрация: 09.08.2020

Сообщений: 46

22.09.2021, 18:16

 [ТС]

3

January29, вот:
22.09.2021 17:05:44
System.AggregateException: Произошла одна или несколько ошибок. —> Microsoft.WebTools.Shared.Exceptions.WebToolsExcep tion: При публикации произошла ошибка. Не удалось определить причину ошибки. Дополнительные сведения см. в журнале вывода.
— Конец трассировки внутреннего стека исключений —
—> (Внутреннее исключение #0) Microsoft.WebTools.Shared.Exceptions.WebToolsExcep tion: При публикации произошла ошибка. Не удалось определить причину ошибки. Дополнительные сведения см. в журнале вывода. <—

Microsoft.WebTools.Shared.Exceptions.WebToolsExcep tion: При публикации произошла ошибка. Не удалось определить причину ошибки. Дополнительные сведения см. в журнале вывода.

0

1728 / 1665 / 360

Регистрация: 17.02.2019

Сообщений: 2,645

22.09.2021, 19:46

4

Yes Chad, На всякий случай сделайте бэкап проекта
Я вот полностью не уверен на все 50%. Попробуйте в Visual Studio очистить кеш NuGet по пути: Средства-Параметры-Диспетчер пакетов NuGet-Общие.
Возможно И там же Средства-Параметры-Диспетчер пакетов NuGet-Источники пакетов. Выбрать внизу Источники пакетов (компьютер):. Возможно что то с сайтом https://api.nuget.org/v3/index.json. Возможно что то его блочит.

Добавлено через 16 минут
Вот мысля проскочила наверно Учетная запись добавлена в Visual Studio

1

3 / 3 / 1

Регистрация: 09.08.2020

Сообщений: 46

22.09.2021, 19:52

 [ТС]

5

January29, к сожалению, данный способ не помог. К слову, данная ошибка возникает в любом (даже пустом) проекте.
Учетная запись не добавлена в Visual Studio.

0

1728 / 1665 / 360

Регистрация: 17.02.2019

Сообщений: 2,645

22.09.2021, 20:43

6

Вот только сейчас опубликовал. Все норм. Ну да ладно.
Обновите студию до последней версии, если не обновляли. Попробуйте восстановить через Visual Studio Installer.

Не по теме:

Будем думу думать.

1

1728 / 1665 / 360

Регистрация: 17.02.2019

Сообщений: 2,645

26.09.2021, 22:51

7

Yes Chad,как то так пишут.

Решение:

Эта ошибка возникает, когда, по крайней мере, насколько мне известно, в Visual Studio 2019 были текущие обновления. Когда я столкнулся с этой ошибкой, у меня были другие приложения в решении, похоже, что Visual Studio испытывает проблемы при создании других проектов, включенных в то же решение. Если вам нужно узнать больше о вашем конкретном сценарии проекта, проверьте окно вывода в Visual Studio на наличие сведений об ошибках. Это полезно при диагностике проблемы, например, в ошибке, зарегистрированной в консоли вывода (Сборка + IntelliSense), может быть указано: «Платформа RuntimeIdentifier» win-x64 «и платформа X86 должны быть совместимы», тогда вы будете знать, что вам нужна одна и та же платформа как в профиле платформы, так и в профиле публикации.
1. Остановите или отмените построение приложения, если сборка застряла.
2. Убедитесь, что вы сохранили свои изменения
3. Закройте Visual Studio и снова откройте свой проект.
4. Когда проект загрузится в Visual Studio 2019, очистите решение
4. Затем перестроить решение
5. После перестроенние решения опубликуйте.

0

3 / 3 / 1

Регистрация: 09.08.2020

Сообщений: 46

26.09.2021, 23:05

 [ТС]

8

Лучший ответ Сообщение было отмечено January29 как решение

Решение

Я нашел решение. Nuget.org начал принудительно использовать TLS 1.2 (и отказался от поддержки TLS 1.1 и 1.0) в начале 2020-го года. Это и вызывало ошибку при публикации приложения в Visual Studio. В Windows 7 TLS 1.2 по умолчанию отключен, однако его можно включить.
Решение было найдено здесь:https://github.com/NuGet/NuGetGallery/issues/8176

1

IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

26.09.2021, 23:05

Помогаю со студенческими работами здесь

Ошибка при публикации приложения MVC с базой MS SQL Server подход Database First
Пытаюсь опубликовать приложение на локальной машине (использую Visual Studio 2013, MS SQLServer…

Стала возникать «Ошибка при создании формы» после публикации
Накануне вечером запускал нормально.
После полез в свойства проекта, воспользовался функцией…

Ошибка публикации приложения
Начал изучать VB.NET
Написал небольшой код в Visual.Studio. Пытаюсь опубликовать решение, для…

Ошибка публикации приложения
Почему Visual Basic выдает такие ошибки? При отладке программа работает отменно :(
Ошибка1 Не…

Ошибка после публикации сайта на Somee.com
Здравствуйте, зарегистрировал свой сайт, на хостере Somee.com
После публикации, в момент…

Ошибка 500 на хосте, после публикации сайта
см. что на экране… и как преодолеть?
Ошибка 500 на хосте, после публикации сайта в visual…

Ошибка браузера CefSharp после публикации проекта
в студии все замечательно работало, но после публикации проекта, при входе в форму, где реализован…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

8

Содержание

Представляет одну или несколько ошибок, происходящих во время выполнения приложения.

  • Пространство имен: System

  • Сборка: mscorlib (в mscorlib.dll)

Иерархия наследования

      • System.AggregateException

Синтаксис

public class AggregateException : Exception, ISerializable, _Exception

Конструкторы

Тип Имя Описание
Конструктор AggregateException() Инициализирует новый экземпляр класса AggregateException системным сообщением, содержащим описание ошибки.
Конструктор AggregateException(String) Инициализирует новый экземпляр класса AggregateException указанным сообщением, содержащим описание ошибки.
Конструктор AggregateException(String, Exception) Инициализирует новый экземпляр класса AggregateException указанным сообщением об ошибке и ссылкой на внутреннее исключение, вызвавшее это исключение.
Конструктор AggregateException(IEnumerable<Exception>) Инициализирует новый экземпляр класса AggregateException со ссылками на внутренние исключения, вызвавшие данное исключение.
Конструктор AggregateException(Exception[]) Инициализирует новый экземпляр класса AggregateException со ссылками на внутренние исключения, вызвавшие данное исключение.
Конструктор AggregateException(String, IEnumerable<Exception>) Инициализирует новый экземпляр класса AggregateException с заданным сообщением об ошибке и ссылками на внутренние исключения, вызвавшие данное исключение.
Конструктор AggregateException(String, Exception[]) Инициализирует новый экземпляр класса AggregateException с заданным сообщением об ошибке и ссылками на внутренние исключения, вызвавшие данное исключение.

Свойства

Методы

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Closed

wpitallo opened this issue

May 8, 2019

· 3 comments

Labels

area-hosting

Includes Hosting

area-runtime

Includes: Azure, Caching, Middleware, Websockets, Kestrel, IIS, ANCM, HttpAbstractions

Comments

@wpitallo

Hi, I just upgraded to .Net core 2.2.4 from 2.1 and I am getting the following error the first time that I await a task:

System.AggregateException: One or more errors occurred. (Object reference not set to an instance of an object.) ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at Service.ExecuteAsync(CancellationToken cancellationToken) in C:Service.cs:line 71
   at Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor.ExecuteAsync(Func`2 callback)
   --- End of inner exception stack trace ---
   at Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor.ExecuteAsync(Func`2 callback)
   at Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor.StartAsync(CancellationToken token)
---> (Inner Exception #0) System.NullReferenceException: Object reference not set to an instance of an object.
   at Service.ExecuteAsync(CancellationToken cancellationToken) in service.cs:line 71
   at Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor.ExecuteAsync(Func`2 callback)<---

This is happening inside a hosted service. Also it throws the exception but the task does complete. Then any awaits after that work perfectly so the error only occurs the first time.

@Eilon

The exceptions seem to be coming from Service.ExecuteAsync, in Service.cs. Is that your code? Also, if you catch the AggregateException in a debugger, what are the inner exceptions (aggregate exception is just a container for multiple inner exceptions, which have the real info)?

@davidfowl

Can you provide a minimal repro with sample code.

@wpitallo

I found the issue, I was creating the singleton hosted service twice. in startup.cs. It would be great if we could get more intuitive error messages for these kind of issues. There were no inner exceptions or anything in the error message that points to the actual error.

Thanks for the help!

@msftbot
msftbot
bot

locked as resolved and limited conversation to collaborators

Dec 3, 2019

@JunTaoLuo
JunTaoLuo

added
the

area-runtime

Includes: Azure, Caching, Middleware, Websockets, Kestrel, IIS, ANCM, HttpAbstractions

label

Jan 28, 2021

Labels

area-hosting

Includes Hosting

area-runtime

Includes: Azure, Caching, Middleware, Websockets, Kestrel, IIS, ANCM, HttpAbstractions

I’m running into a few issues where I call flatten on an AggregateException, but inside there is still ANOTHER AggregateException! This obviously means that they are being propagated up the chain and being rolled into another AggregateException. Is there a way to recursively flatten ALL inner AggregateExceptions? Usually, I’ll use the handle delegate to process these, but it returns false if there is another inner AggregateExceeption. Am I not handling these properly?

EDIT: Since I already am calling Flatten, it appears that the issue is that it’s not being caught until way later in the callstack. Here is the code where I’m calling Flatten(). For use in the stack trace this method is called WriteExceptionRecord(string, FileInfo):

do
{
    try
    {
        using (var stream = file.Open(FileMode.Append, FileAccess.Write, FileShare.None))
        {
            using (StreamWriter writer = new StreamWriter(stream))
            {
                await writer.WriteLineAsync(data);
            }
        }
    }
    catch (AggregateException ex)
    {
        ex.Flatten().Handle((x) =>
        {
            if (x is IOException)
            {
                retryNeeded = true;
                retryLeft--;
                Thread.Sleep(500);
                return true;
            }

            logger.ErrorException("Could not write to exception file: " + data, ex);
            return false;
        });
    }
}
while (retryNeeded && retryLeft > 0);

However, the stack trace shows that it’s not being caught here. Instead it’s being caught way later up the call stack. Below is the trace with some identifying information removed for security reasons:

System.AggregateException: One or more errors occurred. --->      
System.AggregateException: One or more errors occurred. --->
System.IO.IOException: The process cannot access the file 'X:ProductionProductionBatchesDataEntryJPDException.csv' because it is being used by another process.    
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)    
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)    
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)    
   at System.IO.FileInfo.Open(FileMode mode, FileAccess access, FileShare share)    
   at PDI.LoadFileProcessing.<WriteExceptionRecord>d__21.MoveNext() in c:UsersXYZDevelopmentPDIPDILoadFileProcessing.cs:line 328

--- End of stack trace from previous location where exception was thrown ---  
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at PDI.LoadFileProcessing.<ExceptionRecordProcessing>d__17.MoveNext() in c:UsersXYZDevelopmentPDIPDILoadFileProcessing.cs:line 316

--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at PDI.ProcessPipeline.<>c__DisplayClass9.<<ProcessBatch>b__2>d__13.MoveNext() in c:UsersXYZDevelopmentPDIPDIProcessPipeline.cs:line 61

   --- End of inner exception stack trace ---

   --- End of inner exception stack trace ---

---> (Inner Exception #0) System.AggregateException: One or more errors occurred. ---> System.IO.IOException: The process cannot access the file 'X:ProductionProductionBatchesDataEntryJPDException.csv' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at System.IO.FileInfo.Open(FileMode mode, FileAccess access, FileShare share)
   at PeopleDocImporter.LoadFileProcessing.<WriteExceptionRecord>d__21.MoveNext() in c:UsersXYZDevelopmentPDIPDILoadFileProcessing.cs:line 328

--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at PDI.LoadFileProcessing.<ExceptionRecordProcessing>d__17.MoveNext() in c:UsersXYZDevelopmentPDIPDILoadFileProcessing.cs:line 316

--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at PDI.ProcessPipeline.<>c__DisplayClass9.<<ProcessBatch>b__2>d__13.MoveNext() in c:UsersXYZDevelopmentPDIPDIProcessPipeline.cs:line 61

   --- End of inner exception stack trace ---
---> (Inner Exception #0) System.IO.IOException: The process cannot access the file 'X:ProductionProductionBatchesDataEntryJPDException.csv' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at System.IO.FileInfo.Open(FileMode mode, FileAccess access, FileShare share)
   at PDI.LoadFileProcessing.<WriteExceptionRecord>d__21.MoveNext() in c:UsersXYZDevelopmentPDIPDILoadFileProcessing.cs:line 328

--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at PDI.LoadFileProcessing.<ExceptionRecordProcessing>d__17.MoveNext() in c:UsersXYZDevelopmentPDIPDILoadFileProcessing.cs:line 316

--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()    
   at PDI.ProcessPipeline.<>c__DisplayClass9.<<ProcessBatch>b__2>d__13.MoveNext() in c:UsersXYZDevelopmentPDIPDIProcessPipeline.cs:line 61<---

<---

System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> System.IO.IOException: The process cannot access the file 'X:ProductionProductionBatchesDataEntryJPDException.csv' because it is being used by another process.    
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)    
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)    
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)    
   at System.IO.FileInfo.Open(FileMode mode, FileAccess access, FileShare share)    
   at PDI.LoadFileProcessing.<WriteExceptionRecord>d__21.MoveNext() in c:UsersXYZDevelopmentPDIPDILoadFileProcessing.cs:line 328

--- End of stack trace from previous location where exception was thrown ---    
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()    
   at PDI.LoadFileProcessing.<ExceptionRecordProcessing>d__17.MoveNext() in c:UsersXYZDevelopmentPDIPDILoadFileProcessing.cs:line 316

--- End of stack trace from previous location where exception was thrown ---    
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()    
   at PDI.ProcessPipeline.<>c__DisplayClass9.<<ProcessBatch>b__2>d__13.MoveNext() in c:UsersXYZDevelopmentPDIPDIProcessPipeline.cs:line 61

   --- End of inner exception stack trace ---

---> (Inner Exception #0) System.AggregateException: One or more errors occurred. ---> System.IO.IOException: The process cannot access the file 'X:JPDException.csv' because it is being used by another process.    
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)    
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)    
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)    
   at System.IO.FileInfo.Open(FileMode mode, FileAccess access, FileShare share)    
   at PDI.LoadFileProcessing.<WriteExceptionRecord>d__21.MoveNext() in c:UsersXYZDevelopmentPDIPDILoadFileProcessing.cs:line 328

--- End of stack trace from previous location where exception was thrown ---    
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()    
   at PDI.LoadFileProcessing.<ExceptionRecordProcessing>d__17.MoveNext() in c:UsersXYZDevelopmentPDIPDILoadFileProcessing.cs:line 316

--- End of stack trace from previous location where exception was thrown ---    
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()    
   at PDI.ProcessPipeline.<>c__DisplayClass9.<<ProcessBatch>b__2>d__13.MoveNext() in c:UsersXYZDevelopmentPDIPDIProcessPipeline.cs:line 61

   --- End of inner exception stack trace ---    
---> (Inner Exception #0) System.IO.IOException: The process cannot access the file 'X:ProductionProductionBatchesDataEntryJPDException.csv' because it is being used by another process.    
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)    
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)    
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)    
   at System.IO.FileInfo.Open(FileMode mode, FileAccess access, FileShare share)    
   at PDI.LoadFileProcessing.<WriteExceptionRecord>d__21.MoveNext() in c:UsersXYZDevelopmentPDIPDILoadFileProcessing.cs:line 328

--- End of stack trace from previous location where exception was thrown ---    
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()    
   at PDI.LoadFileProcessing.<ExceptionRecordProcessing>d__17.MoveNext() in c:UsersXYZDevelopmentPDIPDILoadFileProcessing.cs:line 316

--- End of stack trace from previous location where exception was thrown ---    
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()    
   at PDI.ProcessPipeline.<>c__DisplayClass9.<<ProcessBatch>b__2>d__13.MoveNext() in c:UsersXYZDevelopmentPDIPDIProcessPipeline.cs:line 61<---

By the way: This is being called by TPL-Dataflow blocks.

Понравилась статья? Поделить с друзьями:
  • Sysprep при запросе операций в режиме ожидания возникла ошибка
  • Syntaxerror invalid syntax ошибка в питоне
  • Sysprep windows 10 ошибка на этапе установки
  • Syntaxerror invalid character in identifier ошибка в питоне
  • Sysprep specialize ошибка на этапе установки виндовс 10