【问题标题】:c# how to pause between 2 function calls without stopping main threadc#如何在不停止主线程的情况下在2个函数调用之间暂停
【发布时间】:2013-04-18 15:13:57
【问题描述】:

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

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


Function Foo()
{
}

谢谢

【问题讨论】:

标签: c# multithreading


【解决方案1】:

试试:

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

【讨论】:

  • 这将浪费一个线程从池中只睡 2 分钟(!)。池是有限的,它可以在该线程上执行大量工作,而不是忙于无所事事
【解决方案2】:
    Task.Factory.StartNew(Foo)
                .ContinueWith(t => Task.Delay(TimeSpan.FromMinutes(2)))
                .ContinueWith(t => Foo());

请不要在线程池上休眠。从不

“线程池中只有有限数量的线程;线程池旨在高效执行大量短任务。它们依靠每个任务快速完成,使线程可以返回池中并被用于下一个任务。” 更多here

为什么是Delay?它在内部使用DelayPromiseTimer,效率更高,效率更高

【讨论】:

  • 和另一个 +1 出于同样的原因。这很容易被忽视:)
【解决方案3】:

如何使用Timer

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

【讨论】:

  • 这不是编译 - 你如何初始化定时器?
【解决方案4】:

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

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

【讨论】:

  • 如果OP使用.NET 4.0或更高版本,最好使用Task
  • 在这种简单的情况下,我会支持Task 更好的说法。
  • 这实际上比使用 Task+Sleep 更好,该解决方案使用专用线程并且不会从池中窃取线程来制作重要的东西,例如睡眠......但是,Task+Delay 更容易跨度>
  • @taras.roshko 这就是我问的原因。我经常看到在没有重新考虑上下文或执行长时间运行的操作的情况下使用 Task
  • @ZdeslavVojkovic 同意。了解内部情况总是更好
【解决方案5】:

您可以使用Timer Class

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();
    }
}

代码未经测试。

【讨论】:

  • Task.Delay 内部也使用定时器
【解决方案6】:
var testtask = Task.Factory.StartNew(async () =>
    {
        Foo();
        await Task.Delay(new TimeSpan(0,0,20));
        Foo();
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 2011-02-09
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    相关资源
    最近更新 更多