简体   繁体   中英

How to implement truly async methods?

I wanted to create a class library with a really sync method, so I wanted to avoid to implement a fake async method that just uses Task.Run to run the sync code.

I have seen that one way is in this way:

public Task miMethodAsync()
{
    TaskCompletionSource<bool> miTcs = new TaskCompletionSource<bool>();
    new Timer(_ =>
        {
            for (Int64 i = 1; i < 10000000; i++)
            {
                //todo my long code
            }
            miTcs.SetResult(true);
        })
        .Change(0, Timeout.Infinite);

    return miTcs.Task;
}

This solution use a timer to return the task, then in 0ms later, it will run the code inside the timer.

This solution doesn't create a new task so it doesn't take a thread form thread pool, so for scalability is good. But I think that this solution, using the timer to run the sync code, it is not an elegant solution, so I'm wondering how really I could implement a really async method.

Because this solution also I could have my sync method and just implement the asyn method in this way:

public Task myMethodAsync()
{
    TaskCompletionSource<bool> miTcs = new TaskCompletionSource<bool>();
    new Timer(_ =>
        {
            myMethodSync();
            miTcs.SetResult(true);
        })
        .Change(0, Timeout.Infinite);

    return miTcs.Task;
}

But as I comment, I think it is not an elegant solution, but really it seems that is not a fake async method like when I run sync code inside a Task.Run() method.

These wrappers that just wrap synchronous code into a pseudo async method are good for nothing. The recommended way is not to create any such wrappers but rather let the API users do Task.Run(SyncMethod) themselves.

Check out this article for the details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM