我希望C#中的计时器在执行后自行销毁.我怎么能实现这个目标?
private void button1_Click(object sender, EventArgs e)
{
ExecuteIn(2000, () =>
{
MessageBox.Show("fsdfs");
});
}
public static void ExecuteIn(int milliseconds, Action action)
{
var timer = new System.Windows.Forms.Timer();
timer.Tick += (s, e) => { action(); };
timer.Interval = milliseconds;
timer.Start();
//timer.Stop();
}
Run Code Online (Sandbox Code Playgroud)
我希望此消息框只显示一次.
我正在使用Threading.Timer,如:
new Timer(new TimerCallback(y=>
{
try
{
Save(Read(DateTime.Now));
// here i want to dispose this timer
}
catch
{
}
}),null,100000,10000);
Run Code Online (Sandbox Code Playgroud)
如何在回调中处理此计时器.或解决方法?更新:让我解释一下情况.我想尝试调用方法"保存",同时抛出异常.如果它工作,我需要停止计时器.
我正在玩HttpListener和Async CTP
class HttpServer : IDisposable
{
HttpListener listener;
CancellationTokenSource cts;
public void Start()
{
listener = new HttpListener();
listener.Prefixes.Add("http://+:1288/test/");
listener.Start();
cts = new CancellationTokenSource();
Listen();
}
public void Stop()
{
cts.Cancel();
}
int counter = 0;
private async void Listen()
{
while (!cts.IsCancellationRequested)
{
HttpListenerContext context = await listener.GetContextAsyncTask(); // my extension method with TaskCompletionSource and BeginGetContext
Console.WriteLine("Client connected " + ++counter);
// simulate long network i/o
await TaskEx.Delay(5000, cts.Token);
Console.WriteLine("Response " + counter);
// send response
}
listener.Close(); …Run Code Online (Sandbox Code Playgroud)