簡體   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