假设一个类有一个public int counter由多个线程访问的字段.这int只是递增或递减.
要增加此字段,应使用哪种方法,为什么?
lock(this.locker) this.counter++;,Interlocked.Increment(ref this.counter);,counter为public volatile.现在,我发现volatile,我已经删除了许多lock语句和使用Interlocked.但是有理由不这样做吗?
我是.Net 4.0的任务的新手,我无法找到我认为基于任务的替换或实现定时器,例如定期任务.有这样的事吗?
更新 我提出了我认为是我的需求的解决方案,即将"计时器"功能包装在具有子任务的任务中,所有任务都利用CancellationToken并返回任务以便能够参与进一步的任务步骤.
public static Task StartPeriodicTask(Action action, int intervalInMilliseconds, int delayInMilliseconds, CancellationToken cancelToken)
{
Action wrapperAction = () =>
{
if (cancelToken.IsCancellationRequested) { return; }
action();
};
Action mainAction = () =>
{
TaskCreationOptions attachedToParent = TaskCreationOptions.AttachedToParent;
if (cancelToken.IsCancellationRequested) { return; }
if (delayInMilliseconds > 0)
Thread.Sleep(delayInMilliseconds);
while (true)
{
if (cancelToken.IsCancellationRequested) { break; }
Task.Factory.StartNew(wrapperAction, cancelToken, attachedToParent, TaskScheduler.Current);
if (cancelToken.IsCancellationRequested || intervalInMilliseconds == Timeout.Infinite) { break; }
Thread.Sleep(intervalInMilliseconds);
}
};
return Task.Factory.StartNew(mainAction, cancelToken);
}
Run Code Online (Sandbox Code Playgroud) 想象一下,我有这样的代码,其中里面的Windows窗体计时器我可以生成一些线程-但我保证只有一个线程使用下面的方法(从答案的一个指示运行位置 -马特·约翰逊):
nb:我们现在假设这种_executing方法有效,我不使用backgroundworker等.
private volatile bool _executing;
private void TimerElapsed(object state)
{
if (_executing)
return;
_executing = true;
if(smth)
{
Thread myThread = new Thread(MainThread1);
myThread.IsBackground = true;
myThread.Start();
}else
{
Thread myThread = new Thread(MainThread2);
myThread.IsBackground = true;
myThread.Start();
}
}
public void MainThread1()
{
try
{
methodWhichAddelementTomyList(); // e.g., inside list.add();
}
finally
{_executing = false;}
}
public void MainThread2()
{
try
{
methodWhichAddelementTomyList(); // e.g., inside list.add();
}
finally
{_executing = false;} …Run Code Online (Sandbox Code Playgroud)