1

Is there a way to get the result of a Task.Run function like this

private Task<bool> UpdteSth(double bla)
        => Task.Run(() =>
        {
            try
            {
                UpdateOneAsync(doStuff);
            }
            catch (Exception exception)
            {
                sentryClient.CaptureException(exception);

                return false;
            }

            return true;
        });

from a caller method like this

public async Task<Entity> Get()
        {
            
                  UpdateSth(double bla);

        }

without having to await UpdateSth so Get can freely do whatever it needs without having to wait to UpdateSth result? I still need to get the result of UpdateSth() to do some logging business but other than that Get should not wait for UpdateSth to be done to continue its job. Clearly, await and Task.FromResult() still make my Get() to wait for the result or UpdateSth to be done so I cannot used those.

Noelia
  • 89
  • 10
  • 1
    `ContinueWith`? – mjwills Aug 04 '21 at 04:13
  • I'm not getting the issue here. If you want to fire-and-forget you just call `UpdateSth(bla);`. What am I missing here? – Enigmativity Aug 04 '21 at 04:34
  • Very unclear what you want to achieve. It sounds like you want to know result of the function **before** it completed... If you find solution to that your really don't need to write any code at that point as you'd know all results in advance... Maybe [edit] question with desired sequence of actions you want to achieve? – Alexei Levenkov Aug 04 '21 at 04:53
  • As a side note, the implementation of the `UpdteSth` method violates [Microsoft's guidelines](https://devblogs.microsoft.com/pfxteam/should-i-expose-asynchronous-wrappers-for-synchronous-methods/ "Should I expose asynchronous wrappers for synchronous methods?") regarding the use of the `Task.Run` method. – Theodor Zoulias Aug 04 '21 at 06:41
  • Related: [Simplest way to do a fire and forget method in C#?](https://stackoverflow.com/questions/1018610/simplest-way-to-do-a-fire-and-forget-method-in-c) and [Best practices to Fire and Forget](https://stackoverflow.com/questions/61820422/best-practices-to-fire-and-forget-an-async-method-to-send-non-essential-metric) – Theodor Zoulias Aug 04 '21 at 06:47

1 Answers1

2

I'm not getting the issue here. If you want to fire-and-forget you just call UpdateSth(bla);. What am I missing here?

Here's an example of what that looks like:

public Task<Entity> Get() =>
    Task.Run(() =>
    {
        double bla = 4.2;
        UpdateSth(bla);
        return new Entity();
    });

This is a trivial example. I feel that there is a more stringent requirement that hasn't been explained in the question.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172