1

I have a specific place in my code, where I am sending an email message. Well, it is not important at all here to wait for this method to be finished, this is just a task which should happen in some near future, but not necessarily RIGHT NOW.

I would like to know if this is safe:

// some stuff here...

Task.Run(SendEmail);

// and here too... but don't wait for the email to be sent, just go!!

Is this alright? Will this method be always executed? It won't lead to any thread-blocking problems, will it (given that the method itself is thread-safe)?

Also, what is a good way to run such a task? Would it be better to call:

SendEmail();

provided that this method is async?

public static async Task SendEmail()
ebvtrnog
  • 4,167
  • 4
  • 31
  • 59

1 Answers1

3

Yes, the method will just 'run'. Unless there is an exception raised in that method, there is nothing that would prevent the method from not get executed successfully.

If you want to know the state of the task after all your work is done, just get the Task instance from the Task.Run method and check the state of it afterwards (you want to await the task before you access it to check if it ended successfully). You could check the Task.Exception property for example.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • May I ask if this is a good idea to use #pragma warning disable CS4014? – ebvtrnog Jun 03 '15 at 17:59
  • 1
    No, it is not. Fix the problem as in [this](https://msdn.microsoft.com/en-us/library/hh873131.aspx) explanation on the compiler warning (I would go for option #2). – Patrick Hofman Jun 03 '15 at 18:01