How do I convert this to an async task?

前端 未结 2 1108
不思量自难忘°
不思量自难忘° 2020-12-11 02:15

Given the following code...

static void DoSomething(int id) {
    Thread.Sleep(50);
    Console.WriteLine(@\"DidSomething({0})\", id);
}

I

2条回答
  •  清歌不尽
    2020-12-11 03:09

    There are two kinds of tasks: those that execute code (e.g., Task.Run and friends), and those that respond to some external event (e.g., TaskCompletionSource and friends).

    What you're looking for is TaskCompletionSource. There are various "shorthand" forms for common situations so you don't always have to use TaskCompletionSource directly. For example, Task.FromResult or TaskFactory.FromAsync. FromAsync is most commonly used if you have an existing *Begin/*End implementation of your I/O; otherwise, you can use TaskCompletionSource directly.

    For more information, see the "I/O-bound Tasks" section of Implementing the Task-based Asynchronous Pattern.

    The Task constructor is (unfortunately) a holdover from Task-based parallelism, and should not be used in asynchronous code. It can only be used to create a code-based task, not an external event task.

    So, given the constraint that you cannot call any existing asynchronous methods and must complete both the Thread.Sleep and the Console.WriteLine in an asynchronous task, how do you do it in a manner that is as efficient as the original code?

    I would use a timer of some kind and have it complete a TaskCompletionSource when the timer fires. I'm almost positive that's what the actual Task.Delay implementation does anyway.

提交回复
热议问题