为什么这个循环不会简单地消失? [英] Why doesn't this loop simply race away?

查看:50
本文介绍了为什么这个循环不会简单地消失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我以为我开始理解新的 async / 等待关键字。然后我有理由写下面的代码,类似于极慢的游戏循环,它只是持续运行,直到标志改变值。这是一个缩短版本的代码:



  public   static  LoopF​​lag { get ;  set ; } =  true ; 

public static void MyEventHandler()
{
Task.Factory.StartNew(()= > WorkerLoop());
}

private static async void WorkerLoop()
{
do
{
Debug.WriteLine( WorkerLoop()...) ;
await Task.Delay( 1000 );

} while (LoopF​​lag);
}





现在,据我所知,等待遇到的关键字,控制只是传回给调用者,并在代码中放置一个延续标记,承诺在任务完成时回到这一点。



我还认为我读过 Task.Delay()创建一个新的任务完成之前的指定时间。



所以,我的问题是,上面的代码是安全的,还是只是尽可能快地旋转,创造了数千个新的 Task.Delay(1000)对象?



任何建议都会感激不尽。



亲切的祝福~Patrick



我的尝试:



我尝试过类似上面代码的东西。它似乎完全符合我的要求,但我不知道如何判断我是否在后台堆积了数千个物体。

解决方案

Task.Delay 将创建一个新的任务(技术上, DelayPromise )和计时器

Task.Delay |参考资料来源 [ ^ ]



但是,在您的示例中,它将每秒执行一次。它不会紧密地在紧密循环中创建新对象,因为 await 确保在任务完成之前该方法的其余部分不会执行。任务完成后,计时器将被处理, DelayPromise 将有资格获得GC。

Hi,

I thought I was beginning to understand the new async/await keywords. Then I had cause to write something like the code below, similar to an extremely slow game loop, which simply runs continuously until a flag changes value. This is a much-shortened version of the code:

public static LoopFlag { get; set; } = true;
	
public static void MyEventHandler()
{
	Task.Factory.StartNew( () => WorkerLoop() );
}

private static async void WorkerLoop()
{
	do
	{
		Debug.WriteLine( "WorkerLoop()..." );
		await Task.Delay( 1000 );

	} while( LoopFlag );
}



Now, as I understand it, when the await keyword it encountered, control simply passes back to the caller, and a 'continuation marker' is placed in the code, a promise to come back to this point when the task has completed.

I also think I read that Task.Delay() creates a new Task that runs for the specified time before completing.

So, my question is, is the code above 'safe', or will it simply whiz round as fast as it can, creating thousands of new Task.Delay( 1000 ) objects?

Any advice would be gratefully received.

Kind wishes ~ Patrick

What I have tried:

I've tried something similar to the code above. It seems to do exactly what I want, but I'm not sure how to tell if I am ending up with thousands of objects piling up in the background.

解决方案

Task.Delay will create a new Task (technically, a DelayPromise) and a Timer:
Task.Delay | Reference Source[^]

However, in your example, it will do this once per second. It won't "whiz round" creating new objects in a tight loop, because the await ensures that the rest of the method doesn't execute until the task has completed. As soon as the task is completed, the Timer will be disposed, and the DelayPromise will be eligible for GC.


这篇关于为什么这个循环不会简单地消失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆