GokcenG
GokcenG

Reputation: 2811

Discarding return value of scope creation side effects

I have such a code block:

public async Task HandleAsync(Func<Task> next, CancellationToken cancellationToken) {
    using (var scope = logger.BeginScope("myName")) {
      await next();
    }
}

Jetbrains Rider suggests changing it to this:

public async Task HandleAsync(Func<Task> next, CancellationToken cancellationToken) {
    using (_ = logger.BeginScope("myName")) {
      await next();
    }
}

And then to this:

public async Task HandleAsync(Func<Task> next, CancellationToken cancellationToken) {
  logger.BeginScope("myName");
  await next();
}

I am wondering if using (_ = logger.BeginScope("myName")) or the last suggestion are identical to my first code block. Would I have any unwanted side effects if I apply the suggestions?

Thanks, Gokcen

Upvotes: 0

Views: 27

Answers (1)

mikelegg
mikelegg

Reputation: 1327

Not knowing the logger implementation, assuming that it relies on using/dispose to output begin/end log messages as this is a common pattern, then ....

No the last suggestion will not be the same as the first 2.

The first 2 explicitly dispose the object returned by logger.So you will get the 'end' log message where you expect.

The last does not. It means that the disposal will happen but you do not know when. So the 'end' log message will be output in an unpredictable place.

Upvotes: 0

Related Questions