'unitOfWork parameter cannot be null' in Background Worker

爷,独闯天下 提交于 2019-12-02 09:45:35

You cannot use async methods with unitOfWork like that in background worker.

Make the changes in these 5 lines:

public void Worker(object sender, DoWorkEventArgs e)
{
    // ...

    workerBlock = new ActionBlock<ValidationObject>(
      (arg) => Validate(arg), // This line #1
      new ExecutionDataflowBlockOptions
      {
          MaxDegreeOfParallelism = 5
      });

    // ...
}

private void Validate(ValidationObject validationObject) // This line #2
{
    try
    {
        using (var contactUnitOfWork = _unitOfWorkManager2.Begin(TransactionScopeOption.RequiresNew))
        {
            Contact contact = validationObject.Contact;
            contact.IsChecked = true;

            AsyncHelper.RunSync(async () => // This line #3
            {                               // This line #4
                await _contactRepository.UpdateAsync(contact);
                await contactUnitOfWork.CompleteAsync();
            });                             // This line #5
        }
    } catch (Exception ex) {
        Logger.Error(ex.ToString());
        throw;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!