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?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow