相关疑难解决方法(0)

使用System.Windows.Forms.Timer.Start()/ Stop()与Enabled = true/false

假设我们在.Net应用程序中使用System.Windows.Forms.Timer,在计时器上使用Start()和Stop()方法与使用Enabled属性之间是否有任何有意义的区别?

例如,如果我们希望在进行某些处理时暂停计时器,我们可以这样做:

myTimer.Stop();
// Do something interesting here.
myTimer.Start();
Run Code Online (Sandbox Code Playgroud)

或者,我们可以这样做:

myTimer.Enabled = false;
// Do something interesting here.
myTimer.Enabled = true;
Run Code Online (Sandbox Code Playgroud)

如果没有显着差异,社区是否就选择哪个选项达成共识?

.net c# timer

31
推荐指数
4
解决办法
2万
查看次数

重复的后台任务

我刚刚开始尝试使用“任务”而不是线程,并尝试实现一个具有后台“清理”任务的对象,只要该对象正在使用,该任务每 5 分钟运行一次,但不应阻止垃圾收集。

一些粗略的东西(这显然不起作用......)

public class Foo : IDisposable
{
    private CancellationTokenSource _tokenSource = new CancellationTokenSource();

    public Foo()
    {
        Cleanup();      
    }

    public void Dispose()
    {
        _tokenSource.Cancel();
    }

    public void Cleanup()
    {
        Task.Delay(TimeSpan.FromSeconds(5), _tokenSource.Token).ContinueWith(t => 
        {
            //Do Work
            if (!_tokenSource.IsCancellationRequested)
            {
                Cleanup();
            }
        }, TaskContinuationOptions.NotOnCanceled);
    }
}
Run Code Online (Sandbox Code Playgroud)

正确的实施方法是什么?

编辑 为了回答 I3arnon 的问题,我使用 IDisposable 因为当我完成对象时,我希望它被垃圾收集。比如没有下面的f.Dispose()(取消任务,f好像不是Garbage Collected,或者cleanup任务取消了。有没有更好的实现方式?

var f = new Foo();
var r = new WeakReference(f);
Thread.Sleep(TimeSpan.FromSeconds(15));
f.Dispose();
f = null;
System.GC.Collect();
Thread.Sleep(TimeSpan.FromSeconds(5));
Console.WriteLine(r.IsAlive);
Run Code Online (Sandbox Code Playgroud)

c# task-parallel-library async-await c#-5.0

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

标签 统计

c# ×2

.net ×1

async-await ×1

c#-5.0 ×1

task-parallel-library ×1

timer ×1