我想要一个能够在与其父级分开的线程中执行定时任务的类,但我有点困惑各个部分属于哪个线程,任何信息将不胜感激。
我的目的是使定时任务独立于父级运行,因为父级包装对象控制的这些任务不止一个。
这就是我想出的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
public class timed_load_process {
private object _lock;
protected string process;
protected Timer timer;
protected bool _abort;
protected Thread t;
protected bool aborting { get { lock (_lock) { return this._abort; } } }
public timed_load_process(string process) {
this._abort = false;
this.process = process;
this.t = new Thread(new ThreadStart(this.threaded));
this.t.Start();
}
protected void threaded() {
this.timer = new Timer(new TimerCallback(this.tick), false, 0, 1000);
while (!this.aborting) {
// do other stuff
Thread.Sleep(100);
}
this.timer.Dispose();
}
protected void tick(object o) {
// do stuff
}
public void abort() { lock (_lock) { this._abort = true; } }
}
由于计时器是在线程内部实例化的,它是在线程内部t
还是在线程内部运行timed_load_process
,我假设操作滴答将在与计时器相同的线程中运行t
。
结束于:
public class timed_load_process : IDisposable {
private object _lock;
private bool _tick;
protected string process;
protected Timer timer;
protected bool _abort;
public bool abort {
get { lock (_lock) { return this._abort; } }
set { lock (_lock) { this.abort = value; } }
}
public timed_load_process(string process) {
this._abort = false;
this.process = process;
this.timer = new Timer(new TimerCallback(this.tick), false, 0, 1000);
}
public void Dispose() {
while (this._tick) { Thread.Sleep(100); }
this.timer.Dispose();
}
protected void tick(object o) {
if (!this._tick) {
this._tick = true;
// do stuff
this._tick = false;
}
}
}