'How can I do ConfigureAwait(false) synchronously

I have Asnyc method and I do the following

await _mediator.Publish(domainEvent).ConfigureAwait(false);

This works fine. But apart from the forementioned Async method, I also have a Synchronous counter part as well. This methhod does not return Task and is not 'async'. So if I have to execute the above line of code in a Synchronous method, how would that be?

Update

Ok, I past the full method here.

public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
  var result = await base.SaveChangesAsync(cancellationToken).ConfigureAwait(false);

  // ignore events if no dispatcher provided
  if (_mediator == null) return result;

  // dispatch events only if save was successful
  var baseEntitieList = ChangeTracker.Entries().Where(entry => entry.Entity.GetType().BaseType?.GetGenericTypeDefinition() == typeof(BaseEntity<>))
    .Select(e => e.Entity).ToList();

  foreach (var baseEntity in baseEntitieList)
  {
    var eventsField = baseEntity.GetType().GetField(nameof(BaseEntity<int>.Events));
    var listOfDomainEvents = (List<BaseDomainEvent>)eventsField!.GetValue(baseEntity)!;
    if (listOfDomainEvents.Any())
    {
      foreach (var domainEvent in listOfDomainEvents)
      {
        await _mediator.Publish(domainEvent).ConfigureAwait(false);
      }
    }
  }
    
  return result;
}

And now the Sync counter part I am talking about. Note this is not async method and does not return Task of int, but rather returns just int.

public override int SaveChanges()
{
  var result = SaveChangesAsync().GetAwaiter().GetResult();

  // ignore events if no dispatcher provided
  if (_mediator == null) return result;

  // dispatch events only if save was successful
  var baseEntitieList = ChangeTracker.Entries().Where(entry => entry.Entity.GetType().BaseType?.GetGenericTypeDefinition() == typeof(BaseEntity<>))
    .Select(e => e.Entity).ToList();

  foreach (var baseEntity in baseEntitieList)
  {
    var eventsField = baseEntity.GetType().GetField(nameof(BaseEntity<int>.Events));
    var listOfDomainEvents = (List<BaseDomainEvent>)eventsField!.GetValue(baseEntity)!;
    if (listOfDomainEvents.Any())
    {
      foreach (var domainEvent in listOfDomainEvents)
      {
        // I am not sure the following is the correct way to execute in sync(not async)

       // Shoud I use the below? I got this idea from the line above, the 3rd line in this code block. 
       // var result = SaveChangesAsync().GetAwaiter().GetResult();
       _mediator.Publish(domainEvent).ConfigureAwait(false).GetAwaiter().GetResult();

       // Or should I use the below as you suggested.
       _mediator.Publish(domainEvent).Wait();
      }
    }
  }

  return result;
}



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source