What is default behavior InsertEvent or InsertEventAsync

152 Views Asked by At

For data providers that allow asynchronous operations, is the standard asynchronous method used?

If not, how do I deify this behavior?

1

There are 1 best solutions below

0
On

I'm not sure what you mean with deify the behavior, but most of the data providers implements both the sync and async methods, for example the FileDataProvider:

https://github.com/thepirat000/Audit.NET/blob/master/src/Audit.NET/Providers/FileDataProvider.cs

However, the base class of the data providers calls the sync method from the virtual async methods, so if a custom data provider does not overrides the async methods, they will just call the sync method within a new task:

https://github.com/thepirat000/Audit.NET/blob/8d410cb919f09d0c35f7c622d2e21913bcc46c59/src/Audit.NET/AuditDataProvider.cs#L58

public virtual async Task<object> InsertEventAsync(AuditEvent auditEvent)
{
    // Default implementation calls the sync operation
    return await Task.Factory.StartNew(() => InsertEvent(auditEvent));
}

Which one is called depends on the context. If you call the Save() or SaveAsync() method on the AuditScope, it will call the sync or async version respectively. And the same happens for Dispose() / DisposeAsync() methods.

Consider the following example:

Audit.Core.Configuration.Setup()
    .UseSqlServer(sql => sql....)
    .WithCreationPolicy(EventCreationPolicy.InsertOnEnd);

using (var scope = AuditScope.Create("test", () => target, null))
{
    target.Status = "Updated";
} // <---- Dispose() will call InsertEvent()

await using (var scope = await AuditScope.CreateAsync("test", () => target, null))
{
    target.Status = "Updated";
} // <---- DisposeAsync() will call InsertEventAsync()