C# 实现一个状态机包含启动停止暂停和超时判断

using System;
using System.Threading;
using System.Threading.Tasks;

enum State
{
    Stopped,
    Running,
    Paused
}

interface IStateHandler
{
    Task Handle(State currentState, CancellationToken cancellationToken);
}

class StoppedStateHandler : IStateHandler
{
    public async Task Handle(State currentState, CancellationToken cancellationToken)
    {
        Console.WriteLine("Starting...");
        await Task.Delay(1000, cancellationToken); // 使用 CancellationToken 控制超时
        Console.WriteLine("Started.");
    }
}

class RunningStateHandler : IStateHandler
{
    public async Task Handle(State currentState, CancellationToken cancellationToken)
    {
        Console.WriteLine("Pausing...");
        await Task.Delay(1000, cancellationToken);
        Console.WriteLine("Paused.");
    }
}

class PausedStateHandler : IStateHandler
{
    public async Task Handle(State currentState, CancellationToken cancellationToken)
    {
        Console.WriteLine("Resuming...");
        await Task.Delay(1000, cancellationToken);
        Console.WriteLine("Resumed.");
    }
}

class StateMachine
{
    private State currentState;
    private readonly IStateHandler[] stateHandlers;

    public event EventHandler<State> StateChanged;

    public StateMachine()
    {
        currentState = State.Stopped;
        stateHandlers = new IStateHandler[Enum.GetValues(typeof(State)).Length];
        stateHandlers[(int)State.Stopped] = new StoppedStateHandler();
        stateHandlers[(int)State.Running] = new RunningStateHandler();
        stateHandlers[(int)State.Paused] = new PausedStateHandler();
    }

    public async Task Start(CancellationToken cancellationToken)
    {
        await HandleStateTransition(State.Stopped, cancellationToken);
    }

    public async Task Pause(CancellationToken cancellationToken)
    {
        await HandleStateTransition(State.Running, cancellationToken);
    }

    public async Task Resume(CancellationToken cancellationToken)
    {
        await HandleStateTransition(State.Paused, cancellationToken);
    }

    public async Task Stop(CancellationToken cancellationToken)
    {
        await HandleStateTransition(State.Stopped, cancellationToken);
    }

    private async Task HandleStateTransition(State nextState, CancellationToken cancellationToken)
    {
        try
        {
            using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
            {
                linkedCts.CancelAfter(5000); // 设置操作超时时间为 5 秒钟
                await stateHandlers[(int)nextState].Handle(currentState, linkedCts.Token);
                currentState = nextState;
                OnStateChanged();
            }
        }
        catch (TaskCanceledException)
        {
            Console.WriteLine("Operation timed out.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error occurred: {ex.Message}");
        }
    }

    protected virtual void OnStateChanged()
    {
        StateChanged?.Invoke(this, currentState);
    }
}

class Program
{
    static async Task Main(string[] args)
    {
        using (var cancellationTokenSource = new CancellationTokenSource())
        {
            StateMachine stateMachine = new StateMachine();
            stateMachine.StateChanged += StateMachine_StateChanged;

            await stateMachine.Start(cancellationTokenSource.Token);
            await stateMachine.Pause(cancellationTokenSource.Token);
            await stateMachine.Resume(cancellationTokenSource.Token);
            await stateMachine.Stop(cancellationTokenSource.Token);

            cancellationTokenSource.Cancel(); // 停止所有操作,包括超时的操作
        }

        Console.ReadLine();
    }

    private static void StateMachine_StateChanged(object sender, State e)
    {
        Console.WriteLine($"State changed: {e}");
    }
}

1,引入了CancellationTokenCancellationTokenSource来控制操作超时。

2,在HandleStateTransition方法中,我们创建一个与传入的CancellationToken关联的新的CancellationTokenSource实例,并在其中设置超时时间。

3,使用linkedCts.Token作为参数调用状态处理程序的Handle方法,以便随时取消操作。如果操作超时或者被取消,我们可以捕获TaskCanceledException并进行相应的处理。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现这个功能,你需要先编写一个控制Web API的服务,然后在Windows Form应用程序中使用该服务。 下面是步骤: 1. 创建一个新的 C# Windows Form应用程序项目。 2. 在项目中添加一个控制器类,例如 `ApiController`,用于处理Web API的启动暂停和重启。 3. 在 `ApiController` 中添加以下代码: ``` public class ApiController : ApiController { HttpSelfHostServer server; public void Start() { var config = new HttpSelfHostConfiguration("http://localhost:8080"); config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional }); server = new HttpSelfHostServer(config); server.OpenAsync().Wait(); } public void Stop() { server.CloseAsync().Wait(); } public void Restart() { Stop(); Start(); } } ``` 在上面的代码中,我们使用 `HttpSelfHostConfiguration` 来配置Web API的路由和端口,然后使用 `HttpSelfHostServer` 来启动Web API服务器。 4. 在 Windows Form 应用程序中添加一个按钮或菜单项,用于启动暂停和重启Web API。 5. 在按钮或菜单项的Click事件处理程序中,实例化 `ApiController` 类并调用其相应的方法。例如: ``` private void btnStart_Click(object sender, EventArgs e) { var apiController = new ApiController(); apiController.Start(); } private void btnStop_Click(object sender, EventArgs e) { var apiController = new ApiController(); apiController.Stop(); } private void btnRestart_Click(object sender, EventArgs e) { var apiController = new ApiController(); apiController.Restart(); } ``` 以上就是使用 .NET 和 C# 创建一个 Windows Form 应用程序并控制 Web API 的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值