开发者

API verbs for an interruptible operation

I have a long running task as part of my application. The task can be started, paused, resumed, and cancelled. I'm trying to find the best interface for these operations.

Two seem clear: Pause and Cancel. This leaves the start and resume operations. I could include both Start and Resume. This has the downside of either requiring the API consumer to check the state before starting/resuming the operation to call the right method, or making the methods aliases of each other. I'm 开发者_如何转开发thinking one possibility is using either Start or Resume, but I don't know which one is the most appropriate.

Does anyone have any examples in the .NET Framework of such behavior? I prefer to follow established patterns whenever they are available.

Edit: The most similar case I found so far is from the Workflow library. WorkflowInstance has the methods:

  • Abort
  • Start
  • Suspend
  • Resume
  • Terminate


"Run" might capture both "Start" and "Resume" - or possibly "Go"?


Not knowing more about what exactly you're doing, I would recommend using something akin to a factory when doing something like this, separating the task from the control. For instance:

public class Task
{
    public TaskController Start()
    {
        TaskController controller = new TaskController(this);

        ... // start the task

        return controller;
    }
}

public class TaskController
{
    private Task task;

    internal TaskController(Task task)
    {
        this.task = task;
    }

    public void Pause() { ... }
    public void Resume() { ... }
    public void Cancel() { ... }
}

In reality, it depends on what you're doing as to whether or not this is appropriate (for instance, this approach would--conceivably--allow you to spawn multiple instances of the task running in parallel; I have no idea if that's appropriate).

Start and Resume are pretty standard terms. If you're looking to include only one of those, I'd choose start. If you're looking for a more suitable term that can serve both purposes, I'd choose something like Run (since both Start and Resume imply something about the state of the task...Resume especially...and IMO Run conveys slightly less than Start).


The interface seems very much like that for a Windows Service. The ServiceController class has Start/Stop/Pause/Continue for it's methods. I could see combining the Start/Continue methods into one, say Run, but then you'd have to handle the difference internally. You might want to consider how you would "reset" the service from a Paused state. If you only had Run, then you'd need to do Stop/Run. Start might automatically reset the state removing the need in this case. I'd examine the use cases and design it from the perspective of the normal path through those.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜