1

I've used async methods for a long time, but I don't know the right way to write my own async method. As I get it, first root(I mean most deep) async method begins from sync method wrapped in a Task? Am I right? What is the right pattern to write such methods? Right now I do it like this:

private async Task DoSomethingAsync()
{
    var tsk = new Task(OnDo);
    tsk.Start();
    await tsk.ConfigureAwait(false);
}

private void OnDo()
{
    // Do stuff ...
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
AsValeO
  • 2,859
  • 3
  • 27
  • 64
  • 5
    If the 'root' method is synchronous, it's synchronous. Don't fake async by just running it on another thread. See [this blog post](http://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html) for more detail – Charles Mager May 17 '15 at 09:56
  • 1
    A good answer would be pages long. I think you need to read a few basi tutorials. – usr May 17 '15 at 09:58
  • @CharlesMager, great article, that explains much. Thanks. – AsValeO May 17 '15 at 10:11
  • 2
    Perhaps my answer [here](http://stackoverflow.com/a/24954336/1870803) can shed some light. – Yuval Itzchakov May 17 '15 at 10:14

1 Answers1

2

The actual answer is too long to post here.

Short answer

No, you should not call async methods from sync methods. The method tree should be asynchronous bottom to top.

For example: Using ASP.NET MVC async methods would be called from async Action methods, see: Using Asynchronous Methods in ASP.NET MVC 4.

public async Task<ActionResult> GizmosAsync()
{
    ViewBag.SyncOrAsync = "Asynchronous";
    var gizmoService = new GizmoService();
    return View("Gizmos", await gizmoService.GetGizmosAsync());
}

Using WPF applications, you should have async void event methods, that call your asynchronous methods.

private async void button1_Click(object sender, RoutedEventArgs e)
{
    textBlock1.Text = "Click Started";
    await DoWork();
    textBlock2.Text = "Click Finished";
}

Either way, the question is too broad.

  • What is your "to be implemented" method?
  • why do you want it to be async?
  • What environment are you using?

In general async is used for I/O operations(databases, network, file read/write) or parallelism.

Community
  • 1
  • 1
annemartijn
  • 1,538
  • 1
  • 23
  • 45