private void StartTask(object sender, FileSystemEventArgs e) { Task task = new Task(() => { var orders = _parser.ManualParse(e.FullPath); foreach (var order in orders) { Thread.Sleep(50); IUnitOfWork uow = new EFUnitOfWork(); IOrderService service = new OrderService(uow); try { lock (_lockObj) { if (!_cancelToken.IsCancellationRequested) { service.AddOrder(order); _logger.Info($"{order.Product} added from file {e.Name}\t Task - {Task.CurrentId}"); } else { _logger.Info("Task stopped"); break; } } } catch (Exception) { _logger.Info("Can't add record to database"); throw new InvalidOperationException("Can't add record to database"); } finally { service.Dispose(); uow.Dispose(); } } if (!_cancelToken.IsCancellationRequested) { _directoryHandler.Move(e.FullPath, e.Name); } }, _cancelToken.Token); task.Start(_taskScheduler); }