简体   繁体   English

异步无限循环

[英]Async Infinite Loop

I'm programming a C# software and it has some functions which make like a check-in on my server 5 in 5 seconds (they send http request, but it doesn't matter for my problem).我正在编写一个 C# 软件,它有一些功能,比如在 5 秒内在我的服务器 5 上签到(它们发送 http 请求,但这对我的问题无关紧要)。 Here is the code:这是代码:

    log();

    while (true)
    {

        alive(); // this sends an http request to my server
        Thread.Sleep(5000); // sleep for 5 seconds avoiding computer overcharge
    }

    MessageBox.Show("after infinite loop"); // this is never executed but i pretend to do so

So, my problem is: I got an infinite loop and after that infinite loop I want to write ANOTHER infinite loop which runs asynchronously and does something each 100ms.所以,我的问题是:我得到了一个无限循环,在那个无限循环之后,我想编写另一个异步运行的无限循环,每 100 毫秒执行一次操作。 Of course "that something" i cannot write it inside the existing loop because that loop is executed 5 in 5 seconds.当然,“那个东西”我不能将它写在现有循环中,因为该循环在 5 秒内执行了 5 次。 I got to code a lot of infinite loops like those, each one being executed independently from another (or asynchronously) with different times.我必须编写很多这样的无限循环,每个循环都在不同的时间独立于另一个(或异步)执行。

I have searched a lot and my conclusion is to write every loop asynchronously.我搜索了很多,我的结论是异步编写每个循环。 My question is: how to do that?我的问题是:该怎么做? Every code I found was completely incomprehensible for me.我发现的每一个代码对我来说都是完全不可理解的。 I simply couldn't understand them.我简直无法理解他们。 So, if you have a better option than async infinite loops (which i think is the best option indeed), you can speak about it, otherwise i need some help coding this async infinite loops...所以,如果你有比异步无限循环更好的选择(我认为这确实是最好的选择),你可以谈论它,否则我需要一些帮助来编码这个异步无限循环......

Sorry for my bad english, thanks in advance抱歉我的英语不好,提前谢谢

var loop1Task = Task.Run(async () => {
 while (true) {
  await Task.Delay(5000);
 }
});

var loop2Task = Task.Run(async () => {
 while (true) {
  await Task.Delay(100);
 }
});

Now you have two loops.现在你有两个循环。 You can add code to them.您可以向它们添加代码。

and after that infinite loop...在那个无限循环之后......

That's not really what "infinite" means:)这不是“无限”的真正含义:)

You can have two simultaneous running processes, simply put them in their own threads.您可以有两个同时运行的进程,只需将它们放在各自的线程中即可。 This would also have the added benefit that your application host isn't blocked by your loop, so you'd be free to do other things with the application host.这还有一个额外的好处,即您的应用程序主机不会被您的循环阻塞,因此您可以自由地使用应用程序主机做其他事情。 (And it doesn't appear to be "frozen" to the host system.) (而且它似乎并没有被主机系统“冻结”。)

It could be something as simple as this...它可能像这样简单......

public class Worker
{
    public void DoWork()
    {
        while (true)
        {
            alive(); // this sends an http request to my server
            Thread.Sleep(5000); // sleep for 5 seconds avoiding computer overcharge
        }
    }
}

Then to start it as a thread:然后将其作为线程启动:

var workerObject = new Worker();
var workerThread = new Thread(workerObject.DoWork);
workerThread.Start();

You can send a variety of information and signals to threads to provide them with data from the consuming code and to control them while they're running.您可以向线程发送各种信息和信号,以向它们提供来自使用代码的数据并在它们运行时控制它们。 (Since you certainly wouldn't want runaway threads that you can't interact with.) So this is just a very simple example to get you started and illustrate the concept. (因为您当然不希望无法与之交互的失控线程。)所以这只是一个非常简单的示例,可以帮助您入门并说明概念。

You can find a lot more information about and more complete examples on MSDN , among a number of other places.您可以在 MSDN以及许多其他地方找到更多有关信息和更完整的示例。

You can do it using async await as follows:您可以使用 async await 执行此操作,如下所示:

Create an async calling method that will call your multiple methods having infinite loop in non blocking way.创建一个异步调用方法,它将以非阻塞方式调用具有无限循环的多个方法。

private async void Method1()
{

DoSomeInfiniteWork1(); //Don't use await here

MessageBox.Show("after First infinite loop"); //now it will executed instantly after calling DoSomeInfiniteWork1 method having infinite while loop.

DoSomeInfiniteWork2();

...some other task
}

Create first method async having infinite loop as follows:创建具有无限循环的第一个异步方法如下:

static bool cancelwork1=false;
private async Task DoSomeInfiniteWork1()
{
log();
    while (true)
    {
        //break logic to exit the loop if required
        if(cancelwork1)
        break;

        alive(); // this sends an http request to my server
        Task.Delay(5000); // Replace Thread.Sleep with Task.Delay
    }
}

Create second method having another infinite loop:创建具有另一个无限循环的第二个方法:

static bool cancelwork2=false;
private async Task DoSomeInfiniteWork2()
{

while (true)
    {
        //break logic to exit the loop if required
        if(cancelwork2)
        break;

       DoSomeOtherWork();// Do your other work 
       Task.Delay(5000); // Replace Thread.Sleep with Task.Delay
    }

}

Thanks !!谢谢 !!

Follow these steps:按着这些次序:

  • Put your loops inside their own methods把你的循环放在它们自己的方法中
  • use Task.Factory.StartNew(() => {methodname}());使用Task.Factory.StartNew(() => {methodname}());
  • use Task.Factory.StartNew(() => {methodname}());使用Task.Factory.StartNew(() => {methodname}()); to call them.打电话给他们。

You need to use System.Threading.Tasks for this, which may have been added by default when you created the project, but if not, you'll need to add it.您需要为此使用System.Threading.Tasks ,它可能在您创建项目时默认添加,但如果没有,则需要添加它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM