用C#中的yield实现Coroutine框架

C#笔记 协程coroutines yield return coroutines在unity里用处多多,用的好可以大量简化代码。 例如: 让loading场景绘制进度条不阻塞,这里异步加载关卡的函数还是必须的。 简化编写不同阶段不同行为的GameObject。 等等。从IEnumerator和IEnumerable开始 看起来是枚举,其实在c#里的意思是迭代器(IEnumerator)和可迭代的(IEnumerable),这个不要阐述错误理解。 阅读详情

最近看到Unity3D中的Coroutine,思路相当值得借鉴。

 

在服务器(尤其是基于事件驱动框架的服务器)编程中,异步操作是难以避免的。传统的异步操作会因为大量的回调操作造成逻辑的支离破碎,再加上状态维护和各种异常处理,很容易就将代码的复杂度提升到外星人才能理解的程度。

比如,有这样一个宠物AI:

等待主人下达移动命令;

移动到目标地点;

等待3秒钟;

喊话;

 

常用的编程模式(非轮询):

 

借助C#的event和lambda,已经使这些逻辑变得比大多数语言要简单了。

如果引入Coroutine框架,则更为简洁:

 

更进一步,可以组合多个事件等待以实现更复杂的逻辑:

 

 

 

C#中Coroutine的深层研究 最近用Coroutine协同程序取代Update的人越来越多,故此我对Coroutine进行了一些研究,以进一步了解该函数的作用,好加快往后游戏的开发效率。 这段文章主要是对拥有一定Coroutine只是的朋友们,若还不了解Coroutine的话可以先去看看Unity3D的文档,再过来做进一步的深层了解。 首先先贴上一段代码: public class ResearchCoroutine 阅读详情

相关推荐

C#迭代器(IEnumerator)与Unity协程(Coroutine)

C#迭代器(IEnumerator)与Unity3D协程(Coroutine) 引言: 使用Unity3D避免不了使用协程(Coroutine),他提供了另一种流程控制的方法,但是如果了解不够深入,会造成不知道什么时候代码会被执行,从而产生不可预知的错误。这篇文章尽可能用通俗的语言和例子解释迭代器和协程的由来和工作原理,本人能力有限,不对之处敬请指正。 一.C#篇:

lijianpeng1024的专栏 4951

c# 纤程 FiberTaskScheduler

c# 纤程 FiberTaskScheduler

大黄鸭在发光的专栏 1335

【C#】 协程 Coroutine 探索

Coroutine ≠ 多线程 以下解释全部基于Unity中: Coroutine的执行仍然在MainThread中进行 Unity 使用StartCoroutine(IEnumertor)来开启协程,yield return 来进行返回 在协程中开启协程过程为栈操作 Unity中 : yield return null ; //将在下一帧中从该现场继续执行 yield returnWaitForEndOfFra...

@Go Nowhere Fast 1558

c# 多线程 执行事件 并发_并发-并行-阻塞-非阻塞-异步-同步-长连接-短连接-进程-线程-协程...

并行和并发并行(parallel):指在同一时刻,有多条指令在多个处理器上同时执行。所以无论从微观还是从宏观来看,二者都是一起执行的。并发(concurrency):指在同一时刻只能有一条指令执行,但多个进程指令被快速的轮换执行,使得在宏观上具有多个进程同时执行的效果,但在微观上并不是同时执行的,只是把时间分成若干段,使多个进程快速交替的执行。并行在多处理器系统中存在,而并发可以在单处理器和多处理...

weixin_39618824的博客 1013

C# IEnumerator yield 浅析

先看一个很简单的例子: using System; using System.Collections.Generic;   namespace ConsoleApplication4 {     class Program     {         //一个返回类型为IEnumerable<int>,其中包含三个yield return         public...

icebergliu1234的博客 1839

C++20中的协程(Coroutine)

目录C++20中的协程(Coroutine)那么,什么是协程?那么这么好用的协程,是不是只要C++20一推出,我们加上一个关键字就能直接把异步调用转化为同步调用呢?协程函数和Awaitable类那么,到底要如何使用协程呢?写在最后 C++20中的协程(Coroutine) 从2017年开始, 协程(Coroutine)的概念就开始被建议加入C++20的标准中了,并已经开始有人对C++20协程的提案进行了介绍。1事实上,协程的概念在很早就出现了,甚至其他语言(JS,Python,C#等)早就已经支持了协程。

Ninsun的博客 1万+

Fiber的理解

Fiber的理解

qq_45803050的博客 1644

C#中Coroutine的深度研究

协程是一种特殊的子程序,它可以在执行过程中暂停并在稍后的时间点继续执行。与普通的函数不同,协程可以保存其状态,并在下次执行时恢复该状态。这使得我们可以编写更加灵活和可读性强的代码。在C#中,协程是通过语句来实现的。当执行到语句时,协程会将当前状态保存,并返回一个值给调用者。当再次调用协程时,它会从上次保存的状态处继续执行。协程是一种强大的编程技术,可以简化异步编程和控制流程。在C#中,我们可以使用语句来实现协程功能,使代码更加简洁和易于维护。

CodeLancerX的博客 491

Fiber的深度理解

react15在render阶段的reconcile是不可打断的,这会在进行大量节点的reconcile时可能产生卡顿,因为浏览器所有的时间都交给了js执行,并且js的执行时单线程。为此r...

文摘资讯 788

【vue看板】

大屏看板提示:以下是本篇文章正文内容,下面案例可供参考提示:这里对文章进行总结:代码量较多,看板中的。

weixin_46223284的博客 2772

晶圆测试(wafer sort)全流程解析:从探针卡到良率统计的实战指南

本文详细解析了晶圆测试(wafer sort)的全流程,从探针卡选型到良率统计的实战指南。涵盖了12英寸先进制程产线的关键技术,包括探针卡系统、测试程序开发、产线自动化集成及数据分析,特别聚焦多站点并行测试的时序优化和接触阻抗异常排查,帮助工程师提升测试效率与准确性。

weixin_29279153的博客 731

Unity3D中的Coroutine 与 Yield

转自:http://blog.youkuaiyun.com/blues1021/article/details/40959915             http://www.cnblogs.com/manuosex/p/3726475.html Yield的基本用法: 最近,需要需要用unity 3d做点东西,但是了碰到了延迟加载问题,我总结余下:   Coroutines & Yield是

随缘,随心 2141

滞回比较器电路详细分析

滞回比较器是一种用于检测两个不同电压值并使比较器输出高电平或低电平的电路。滞回比较器的特点是具有迟滞特性,即当输入电压高于某一阈值时,比较器输出高电平,当输入电压低于另一阈值时,比较器输出低电平,而在这两个阈值之间,比较器的输出保持不变。比较器通常有两个模拟电压输入端UIN+和UIN-以及一个数字状态输出端UOUT。当UIN+大于UIN-时,UOUT为高电平;当UIN+小于UIN-时,UOUT为低电平。根据具体的系统定义,这两种电位的具体数值可以有所不同。

LuDvei的博客 2万+

Unity3D中的Coroutine详解

Unity中的Coroutine原理猜测:虚拟机分段执行机制, 同类型嵌套用栈存放实现串行执行. Unity中使用yield Coroutine需要注意的问题

自由理想的足迹 5万+

双目视觉入门实战:用Matlab标定相机,再到Python OpenCV完成测距的完整链路

本文详细介绍了双目视觉技术的完整实现流程,从Matlab相机标定到Python OpenCV测距的全链路实践。重点解析了Matlab与OpenCV的参数转换技巧,以及立体校正、视差计算等关键步骤的代码实现,帮助开发者快速掌握双目测距系统的搭建方法。

weixin_29166013的博客 445

PCL 点云格式转换【2024最新版】

常见点云格式转化汇总包括txt、stl、csv、ply、obj、xyz、las等。博客长期更新,本文最近一次更新时间为:2024年9月14日,代码更新至PCL1.14.1版本。

点云侠的博客 39万+

关于C#迭代器与Unity的Coroutine

1.C#迭代器原理 2.Coroutine的返回类型为IEnumerator,使用yield return返回,它与迭代器有什么联系 3.实现一个Coroutine

henger_的博客 844

【已解决】WorkBuddy 国内版与国际版共存 + 关闭自动更新 教程

本文介绍在Windows系统中同时安装并共存WorkBuddy国内版与国际版的完整方案,通过修改product.json文件关闭启动自动更新,修复缓存配置污染问题,确保两版本互不干扰、数据独立。重点解决因共享身份标识导致的更新源错乱、进程锁冲突及自动覆盖风险,提供命令行备份与修改步骤,并强调手动升级时需避免使用应用内更新功能,以规避平台参数错位缺陷。

人生是一场修行 1483

Unity3D中的Coroutine具体解释

本文太乱,推荐frankjfwang的:全面解析Coroutine技术 Unity中的coroutine是通过yield expression;来实现的。官方脚本中到处会看到这种代码。 疑问: yield是什么? Coroutine是什么? unity的coroutine程序运行流程怎么那么奇怪? unity中的coroutine原理是什么,怎么实现的? 使用un...

aodiyi6351的博客 215

提示工程ROI计算模板:架构师私藏Excel表(含自动计算)

花3个人力优化提示词,到底能带来多少实际收益?“这个提示工程项目值得做吗?投入10万成本,多久能回本?“不同LLM应用的提示词优化优先级怎么排?全凭经验拍脑袋?当前90%的企业在提示工程投入上缺乏标准化的量化评估方法,导致资源浪费(盲目投入无回报项目)或错失机会(低估高价值优化点)。ROI = (总收益 - 总成本) / 总成本 × 100%对于提示工程,总成本=显性成本+隐性成本,总收益=直接收益+间接收益(后文会详细拆解)。提示工程的价值不是“玄学”,而是可以用数据量化的投资行为。本文分享的。

AI开发架构师 1073

Open3D 机载点云电力线提取【2025最新版】

传统方法实现的机载点云电力线分割提取。博客长期更新,本文最新更新时间为:2025年3月23日。

点云侠的博客 4468

C#迭代器和Unity的Coroutine原理

本文介绍了C#中的枚举和迭代器。枚举提供了foreach遍历集合的机制,由枚举器和可枚举对象组成。枚举器实现IEnumerator或IEnumerator<T>接口,提供只读、只能向前的光标。可枚举对象实现IEnumerable或IEnumerable<T>接口,提供GetEnumerator方法返回枚举器。示例代码展示了foreach的底层实现。迭代器是枚举器的生产者,foreach是枚举器的使用者。

omegayy的专栏 1162

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Unity的协程Coroutine实现原理和C#的IEnumerator、IEnumeratable、yield 介绍

Unity的协程实现一直困扰着我,花了很多时间去翻资料也没看出个所以然,今天又去查阅相关博客,总算有个比较清晰的理解,记录一下。 想要弄清楚Coroutine的机制,就必须先弄清楚什么是IEnumerator,IEnumeratable,yield。 IEnumerator和IEnumeratable: 这两个接口的代码非常简单,但是理解起来其实也需要一点思路。先贴出它们的代...

PresleyGo的博客 1702

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

unity协程_Unity中的Yield Return是个什么鬼?

写完以后发现了这篇博文,看完觉得自己太浅薄了。Coroutine,你究竟干了什么?_tkokof1的专栏-优快云博客​blog.youkuaiyun.com好多年没怎么用Unity,回过头来一看已经2020版本了,哈哈,当年最早还是用1.7版本,一帮菜鸟级码农在出租屋里写着大量if嵌套的丑陋代码,后来自己跟着一位大神开始C#+Unity之不归路,当时还是3.5版本,而自己做了个小项目的时候升到了4.3。真是...

weixin_39723010的博客 1097

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

coroutine yield 多线程

<br />Coroutine&yield<br />Coroutine效果类似Objective c中的nstread,创建一个线程。但它不是多线程。<br />StartCoroutine,StopCoroutine,StopAllCoroutines。<br />Js和c#的调用不同,js不用自己实现协同操作。C#需要调用函数实现协同操作。<br />Yield效果类似sleep函数,休眠线程。但不是sleep函数。<br /> <br /> <br />多线程处理<br />网上拔下来的例子。在这喷

Rey 2633

unity coroutine

http://gad.qq.com/article/detail/695 使用Unity 3D引擎的同学,对于Coroutine(协程)的使用肯定也是非常熟悉的了。然而Coroutine背后的技术以及具体的实现方式、运行流程如何,恐怕并不是那么容易说得清楚。 本文尝试通过分析Unity 3.5.7版本的源代码,来厘清这一关键技术细节。(由于U...

aikb6223的博客 208
上一篇: Protobuf生态圈(上)简介和数据库粘合层
cometeor
博客等级 码龄18年 71粉丝 21原创
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值