相关疑难解决方法(0)

如何只在C#中运行一次计时器?

我希望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)

我希望此消息框只显示一次.

c#

7
推荐指数
3
解决办法
2万
查看次数

我可以在回调中处理Threading.Timer吗?

我正在使用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)

如何在回调中处理此计时器.或解决方法?更新:让我解释一下情况.我想尝试调用方法"保存",同时抛出异常.如果它工作,我需要停止计时器.

.net dispose timer callback

6
推荐指数
1
解决办法
7493
查看次数

等待TaskEx.Delay

我正在玩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)

c# asynchronous

3
推荐指数
1
解决办法
4566
查看次数

标签 统计

c# ×2

.net ×1

asynchronous ×1

callback ×1

dispose ×1

timer ×1