繁体   English   中英

c#如何在不停止主线程的情况下在两个函数调用之间暂停

[英]c# how to pause between 2 function calls without stopping main thread

c#如何在不停止主线程的情况下在两个函数调用之间暂停

Foo();
Foo(); // i want this to run after 2 min without stopping main thread


Function Foo()
{
}

谢谢

尝试:

Task.Factory.StartNew(() => { foo(); })
    .ContinueWith(t => Thread.Sleep(2 * 60 * 1000))
    .ContinueWith(t => { Foo() });
    Task.Factory.StartNew(Foo)
                .ContinueWith(t => Task.Delay(TimeSpan.FromMinutes(2)))
                .ContinueWith(t => Foo());

请不要在线程池上睡觉。 决不

“线程池中只有有限数量的线程;线程池旨在有效地执行大量的短任务。它们依赖于每个任务快速完成,以便线程可以返回池并用于下一个任务。“ 更多这里

为何Delay DelayPromise内部使用带有Timer DelayPromise ,效率更高,效率更高

如何使用Timer

var timer = new Timer();
timer.Interval = 120000;
timer.Tick += (s, e) =>
{
    Foo();
    timer.Stop();
}
timer.Start();

尝试生成一个新线程,如下所示:

new Thread(() => 
    {
         Foo();
         Thread.Sleep(2 * 60 * 1000);
         Foo();
    }).Start();

您可以使用Timer类

using System;
using System.Timers;

public class Timer1
{
    private static System.Timers.Timer aTimer;

    public void Foo()
    {
    }

    public static void Main()
    {
        Foo();

        // Create a timer with a two minutes interval.
        aTimer = new System.Timers.Timer(120000);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(Foo());

        aTimer.Enabled = true;
    }

    // Specify what you want to happen when the Elapsed event is  
    // raised. 
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Foo();
    }
}

代码尚未经过测试。

var testtask = Task.Factory.StartNew(async () =>
    {
        Foo();
        await Task.Delay(new TimeSpan(0,0,20));
        Foo();
    });

暂无
暂无

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

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