Correct way to expose a cancellable Task API

If I want to expose an API which internally Schedules a sequence of Tasks that should be cancellable by the user. e.g.

public ??? DoWork()
{
    Task t = new .... , myCancellationToken);
    return ???
}

What is the correct object to return for cancellation Control? Is it CancellationTokenSource ?

public CancellationTokenSource DoWork()
{
    CancellationTokenSource source = new ....
    Task t = new .... , source.Token);
    return source;
}

Should I return anything at all? Should I just accept a CancellationToken as an arg and let the user create the token source if needed?

public void DoWork(CancellationToken token)
{
    Task t = new .... , token);
}

What is the most idiomatic way to deal with this?

Answers


Should I just accept a CancellationToken as an arg and let the user create the token source if needed?

This. But you should quite possibly return a Task as well, so that the user can observe when it's completed etc. This is amenable to async/await as well, of course.

You may also want to have overloads:

public Task DoWork()
{
    return DoWork(CancellationToken.None);
}

public Task DoWork(CancellationToken cancellationToken)
{
    ...
}

See the Task-based Asynchronous Pattern for general conventions on this sort of thing.


Need Your Help

Facebook graph api php getting pictures too slow

php json facebook facebook-graph-api

Hi so in my new Facebook application I attempt to load a selection of profile pictures for the users on the screen. The problem is, it just takes way too long. This is what I am currently doing to ...

How to create a JSONArray with GSON

android json gson arrays

Hi in my project i need to create a JSONArray type with the GSON class

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.