У меня есть консольное приложение в качестве веб-задания для обработки уведомлений внутри моего приложения. Процессы запускаются с помощью очереди. Приложение взаимодействует с базой данных SQL Azure с помощью entity framework 6. Вызываемый метод Process () считывает / записывает данные в базу данных.
Я получаю несколько ошибок при обработке сообщений очереди. Они никогда не попадают в очередь на яд, так как успешно повторно обрабатываются через 2-3 раза. В основном ошибки следующие:
Необработанное исключение типа System.StackOverflowException в mscorlib.dll
Ошибка: System.OutOfMemoryException: исключение типа «System.OutOfMemoryException».
Размер пакета по умолчанию - 16, поэтому сообщения обрабатываются параллельно.
Я предполагаю, что настройка Ninject для параллельной обработки сообщений неверна. Следовательно, когда они обрабатываются одновременно, возникают некоторые ошибки, и в конечном итоге они обрабатываются успешно.
Мой вопрос: выглядит ли эта установка нормально? Должен ли я использовать InThreadScope (), возможно, поскольку я не знаю, что параллельная обработка также является многопоточной.
Вот код моего приложения.
Program.cs
namespace NotificationsProcessor
{
public class Program
{
private static StandardKernel _kernel;
private static void Main(string[] args)
{
var module = new CustomModule();
var kernel = new StandardKernel(module);
_kernel = kernel;
var config =
new JobHostConfiguration(AzureStorageAccount.ConnectionString)
{
NameResolver = new QueueNameResolver()
};
var host = new JobHost(config);
//config.Queues.BatchSize = 1; //Process messages in parallel
host.RunAndBlock();
}
public static void ProcessNotification([QueueTrigger("%notificationsQueueKey%")] string item)
{
var n = _kernel.Get<INotifications>();
n.Process(item);
}
public static void ProcessPoison([QueueTrigger("%notificationsQueueKeyPoison%")] string item)
{
//Process poison message.
}
}
}
Here's the code for Ninject's CustomModule
namespace NotificationsProcessor.NinjectFiles
{
public class CustomModule : NinjectModule
{
public override void Load()
{
Bind<IDbContext>().To<DataContext>(); //EF datacontext
Bind<INotifications>().To<NotificationsService>();
Bind<IEmails>().To<EmailsService>();
Bind<ISms>().ToSmsService>();
}
}
}
Код для метода процесса.
public void ProcessMessage(string message)
{
try
{
var notificationQueueMessage = JsonConvert.DeserializeObject<NotificationQueueMessage>(message);
//Grab message and check if it has to be processed
var notification = _context.Set().Find(notificationQueueMessage.NotificationId);
if (notification != null)
{
if (notification.NotificationType == NotificationType.AppointmentReminder.ToString())
{
notificationSuccess = SendAppointmentReminderEmail(notification); //Code that sends email using the SendGrid Api
}
}
}
catch (Exception ex)
{
_logger.LogError(ex + Environment.NewLine + message, LogSources.EmailsService);
throw;
}
}
Обновление - добавлено исключение
Исключение создается сериализатором Json. Вот трассировка стека:
Error: System.OutOfMemoryException: Exception of type ‘System.OutOfMemoryException’ was thrown. at System.String.CtorCharCount(Char c, Int32 count) at Newtonsoft.Json.JsonTextWriter.WriteIndent() at Newtonsoft.Json.JsonWriter.AutoCompleteClose(JsonContainerType type) at Newtonsoft.Json.JsonWriter.WriteEndObject() at Newtonsoft.Json.JsonWriter.WriteEnd(JsonContainerType type) at Newtonsoft.Json.JsonWriter.WriteEnd() at Newtonsoft.Json.JsonWriter.AutoCompleteAll() at Newtonsoft.Json.JsonTextWriter.Close() at Newtonsoft.Json.JsonWriter.System.IDisposable.Dispose() at Newtonsoft.Json.JsonConvert.SerializeObjectInternal(Object value, Type type, JsonSerializer jsonSerializer) at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Type type, Formatting formatting, JsonSerializerSettings settings) at Core.Services.Communications.EmailsService.SendAppointmentReminderEmail(Notificaciones email) in c:\ProjectsGreenLight\EAS\EAS\EAS\Core\Services\Communications\EmailsService.cs:line 489 at Core.Services.Communications.EmailsService.ProcessMessage(String message) in c:\ProjectsGreenLight\EAS\EAS\EAS\Core\Services\Communications\EmailsService.cs:line 124 at Core.Services.NotificacionesService.Process(String message) in c:\ProjectsGreenLight\EAS\EAS\EAS\Core\Services\NotificacionesService.cs:line 56
INotifications.Process
трудно сказать, что там происходит - нет ничего явно неправильного в том, что вы опубликовали. Изучите код вProcess
, чтобы увидеть, есть ли бесконечная рекурсия или что-то, что может вызвать нехватку памяти. - person Victor Hurdugaci   schedule 21.10.2014