110,536
社区成员
发帖
与我相关
我的任务
分享
for()
{
await WriteByteToSerialPort
await WriteByteToSerialPort
}
setTimeout(func,interval)
异步操作的编程方法。一个 c# 程序员也应该熟练设计异步操作流程,不要只会写 for 循环。using System;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
static Timer t;
static void Main(string[] args)
{
var a = new int[5] { 1, 2, 3, 4, 5 };
t = new Timer(h => x(a, 0), null, 1000, -1);
Console.WriteLine("................按任意键结束");
Console.ReadKey();
}
static void x(int[] arr, int index)
{
Console.WriteLine("x--执行,index={0}", index);
t = new Timer(h => y(arr, index), null, 500, -1);
}
static void y(int[] arr, int index)
{
Console.WriteLine("y--执行,index={0}", index);
if (index < arr.Length)
t = new Timer(h => x(arr, index + 1), null, 1500, -1);
else
Console.WriteLine("全部处理完毕,不再调用x了。");
}
}
}
你会看到,异步交互式的程序流程,根本没有什么简单函数 for 循环、while 循环那种变成概念,而是“委托、回调、事件”的编程设计概念。能够把流程倒置理解,这才正确地理解了更加真实地符合自然应用领域需求的异步操作流程。而那种顺序式的函数式编程,只是算个小数字的时候才用的,是刚学编程时都会学到的,但是不是交互式程序设计技术。using System;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
static Timer t;
static void Main(string[] args)
{
var a = new int[5] { 1, 2, 3, 4, 5 };
t = new Timer(h => x(a, 0), null, 1000, -1);
Console.WriteLine("................按任意键结束");
Console.ReadKey();
}
static void x(int[] arr, int index)
{
Console.WriteLine("x--执行,index={0}", index);
t = new Timer(h => y(arr, index), null, 500, -1);
}
static void y(int[] arr, int index)
{
Console.WriteLine("y--执行,index={0}", index);
if (index < arr.Length)
t = new Timer(h => x(arr, index + 1), null, 1500, -1);
else
Console.WriteLine("全部处理完毕,不再调用x了。");
}
}
}
quote]
这里面“委托、回调、事件”在哪里体现,能给解释一下吗,非常感谢!