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?


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

ParentController.apply() Not Working Inside ChildController Because Of IIFEs

javascript angularjs iife

When the IIFE is removed from ParentController in the following snippet, ParentController.apply() works as expected within ChildController.

How to create a virtual directory from file in IIS 8.5

iis iis-8 virtual-directory

I want to import virtual directory setting via file in IIS 8.5, but cannot find an option to do so. In IIS 6 you can:

Understanding require.js for implimenting backbone.js

javascript backbone.js requirejs

I am learning require.js to organizing backbone.js templates. I got several tutorial when I search in GOOGLE. I found different implementations there. That's why I could not understand those codes of

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.