C#中断执行的四种方式

目录

中断执行的四种方式

continue

代码

 执行效果

break

代码

效果

有关中断执行的注意点


中断执行的四种方式

  • continue :立即终止当前的循环(继续执行下一次循环)
  • break :立即终止循环,继续执行循环后面的第一行代码
  • goto :可以跳出循环,到已标记好的位置上
  • return:跳出包含其的函数

相同语句但是中断执行的方式不一样,会出现不同的效果。

continue

代码

using System;

namespace ConsoleApptest
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                if (i % 2 == 1)
                {
                    continue;
                }
                Console.WriteLine(i);
            }
        }
    }
}

 执行效果

break

代码

using System;

namespace ConsoleApptest
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                if (i % 2 == 1)
                {
                    break;
                }
                Console.WriteLine(i);
            }
        }

    }
}

效果

有关中断执行的注意点

  • goto可以跳出循环,但不能跳入
  • 注意continue和break的区别
  • 使用continue应该谨慎 
C# 中,中断事件的执行可以通过多种方式实现。通常情况下,这涉及到线程控制或者通过标志位来停止事件处理器中的逻辑流程。 以下是几种常见的方法: ### 方法一:使用 `Thread.Interrupt` 和多线程机制 如果事件是在单独的线程中运行,则可以利用 `Thread.Interrupt` 来请求中断该线程。需要注意的是,这种方法仅适用于基于线程的场景[^1]。 ```csharp using System; using System.Threading; namespace InterruptEventExecution { class Program { static void Main(string[] args) { Thread thread = new Thread(new ThreadStart(EventHandler)); thread.Start(); Console.WriteLine("Press any key to interrupt the event..."); Console.ReadKey(); try { thread.Interrupt(); // 请求中断线程 } catch (ThreadInterruptedException e) { Console.WriteLine($"Thread was interrupted: {e.Message}"); } } static void EventHandler() { while (true) { try { Console.WriteLine("Executing event handler logic..."); Thread.Sleep(1000); // Simulate work being done } catch (ThreadInterruptedException) { Console.WriteLine("EventHandler has been interrupted."); break; // Exit loop when interrupted } } } } } ``` 此代码展示了如何在线程中运行事件处理程序,并允许主线程中断子线程的工作流[^1]。 --- ### 方法二:使用取消令牌 (`CancellationToken`) 更现代的方式是借助 .NET 提供的 `CancellationTokenSource` 类型。这种方式更加优雅且推荐用于异步编程环境[^4]。 ```csharp using System; using System.Threading; namespace CancellationTokenExample { class Program { static void Main(string[] args) { CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; ThreadPool.QueueUserWorkItem(_ => EventWithCancellation(token)); Console.WriteLine("Press 'Enter' to cancel the operation..."); Console.ReadLine(); cts.Cancel(); // Request cancellation Console.WriteLine("Operation cancelled. Press any key to exit."); Console.ReadKey(); } static void EventWithCancellation(CancellationToken token) { int counter = 0; while (!token.IsCancellationRequested) { Console.WriteLine($"Counter value: {counter++}"); Thread.Sleep(500); } Console.WriteLine("Event processing stopped due to cancellation request."); } } } ``` 上述示例说明了如何通过取消令牌安全地中止长时间运行的任务或事件处理过程[^4]。 --- ### 方法三:设置标志变量 另一种简单的方法是引入布尔类型的标志变量,由外部信号更改其状态以决定是否继续执行当前逻辑[^3]。 ```csharp using System; using System.Threading; namespace FlagBasedInterruption { class Program { private static bool _continueProcessing = true; static void Main(string[] args) { Thread workerThread = new Thread(ProcessEvents); workerThread.Start(); Console.WriteLine("Press Enter to stop event handling..."); Console.ReadLine(); _continueProcessing = false; // Signal to stop workerThread.Join(); // Wait until thread finishes its job Console.WriteLine("Worker thread terminated successfully."); } static void ProcessEvents() { int count = 0; while (_continueProcessing && count < 10) { Console.WriteLine($"Handling event #{count++}"); Thread.Sleep(500); } if (!_continueProcessing) { Console.WriteLine("Event processing interrupted by user input."); } } } } ``` 在此方案中,通过修改共享的 `_continueProcessing` 变量实现了对事件循环的手动干预。 --- ### 总结 以上三种技术分别代表不同的应用场景和技术选型方向。对于简单的同步任务可以选择标志变量;而对于复杂的并发需求则建议优先考虑 `CancellationToken` 的解决方案,因为它提供了更好的灵活性和安全性[^4]。 #### 注意事项 - 如果目标平台支持最新的框架版本,请尽可能采用高级别的抽象工具(如 `Task`/`async-await`),而非手动管理低级线程对象。 - 始终注意异常捕获与资源释放环节,确保即使发生意外也能维持系统的稳定性[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二琳爱吃肉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值