0

我正在使用 C#,Silverlight。

我需要一种方法来根据以秒(或其他时间单位)为单位的某个值初始化倒计时,并且在倒计时结束时我需要执行一些方法。

倒计时必须与主应用程序分开。

4

4 回答 4

2

采用Task.Delay

static void SomeMethod()
{
    Console.WriteLine("Thread ID = " + Thread.CurrentThread.ManagedThreadId);

    Console.WriteLine("performing an action...");
}

static void Main(string[] args)
{
    int someValueInSeconds = 5;

    Console.WriteLine("Thread ID = " + Thread.CurrentThread.ManagedThreadId);

    Task.Delay(TimeSpan.FromSeconds(someValueInSeconds)).ContinueWith(t => SomeMethod());

    // Prevents the app from terminating before the task above completes
    Console.WriteLine("Countdown launched. Press a key to exit.");
    Console.ReadKey();
}

请注意,您关心的唯一代码行是带有Task.Delay. 我已经包含了其他所有内容,以证明该操作在倒计时后执行,并且按照您的要求在另一个线程上执行。

Aviod使用 Timer 类,新的 Task.* API 提供了相同级别的灵活性和更简单的代码。

于 2012-10-03T16:55:23.027 回答
1

使用 System.Timers.Timer 对象。订阅 Elapsed 事件,然后调用 Start。

using System.Timers;
...
some method {
...
    Timer t = new Timer(duration);
    t.Elapsed += new ElapsedEventHandler(handlerMethod);
    t.AutoReset = false;
    t.Start();
...
}

void handlerMethod(Object sender, ElapsedEventArgs e)
{
    ...
}

默认情况下(如上所示),Timer 将用于ThreadPool触发事件。这意味着 handlerMethod 不会与您的应用程序在同一线程上运行。它可以与 ThreadPool 中的其他线程竞争,但不能与池外的线程竞争。您可以设置 SynchronizingObject 来修改此行为。特别是,如果 Elapsed 事件调用 Windows 窗体控件中的方法,您必须在创建控件的同一线程上运行,将 SynchronizingObject 设置为控件将完成此操作。

于 2012-10-03T16:42:01.873 回答
1

在调用事件处理程序时,它们不应被阻塞,它们应立即返回。您应该通过 Timer、BackgroundWorker 或 Thread 来实现这一点(按此优先顺序)。

参考:

using System;
using System.Windows.Forms;
class MyForm : Form {
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.Run(new MyForm());
    }

    Timer timer;
    MyForm() {
        timer = new Timer();
        count = 10;
        timer.Interval = 1000;
        timer.Tick += timer_Tick;
        timer.Start();
    }
    protected override void Dispose(bool disposing) {
        if (disposing) {
            timer.Dispose();
        }
        base.Dispose(disposing);
    }
    int count;
    void timer_Tick(object sender, EventArgs e) {
        Text = "Wait for " + count + " seconds...";
        count--;
        if (count == 0)
        {
            timer.Stop();
        }
    }
}
于 2012-10-03T16:46:10.977 回答
1
DispatcherTimer timer = new DispatcherTimer();

timer.Tick += delegate(object s, EventArgs args)
                {
                    timer.Stop();
                    // do your work here
                };

// 300 ms timer
timer.Interval = new TimeSpan(0, 0, 0, 0, 300); 
timer.Start();
于 2012-10-03T16:50:19.397 回答