S
S
Slavka2017-05-02 23:00:12
C++ / C#
Slavka, 2017-05-02 23:00:12

Designing your own asynchronous functions, which pattern is correct?

public Task<int> Foo()
    {
        var tcs = new TaskCompletionSource<int>();
        Task.Run(() => {
            var result = SomeAction();
            tcs.SetResult(result);
        });
        return tcs.Task;
    }

I just can’t understand what benefit the TaskCompletionSource class plays here, why is it considered bad form to write return Task.Run(...)?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Tom Nolane, 2017-05-02
@tomnolane

I always use this:
//for a method that returns nothing

public async Task Blabla()
{
    await Task.Run(()=>{

     //тут я что-то выполняю

     });
}

//for a method that returns a string type (for example)
public async Task<string> Blabla()
{
    return await Task.Run(()=>{

     return "я возвращаюсь!!!";

     });
}

and that's it.
simply. works. readable.
upd.
Petr - Mercy, reminded)
upd2
Slavka : here is the answer to where TaskCompletionSource is used in practice

P
Peter, 2017-05-02
@petermzg

In your example, the TaskCompletionSource is definitely redundant.
Enough:

public Task<int> Foo()
{
        return Task.Run(() => {
            return SomeAction();
        });
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question