我想一類是能夠在一個線程中分離出來,從它的父執行定時任務,但我有點糊塗了哪個線程的各個部分屬於任何信息,將不勝感激。哪個線程執行方法?
我的目的是使定時任務從父獨立運作,因爲將這些由家長包裝對象控制一個以上。
這是我想出了:
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
的線程內,我認爲操作tick將在與定時器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;
}
}
}
不同於論壇的網站,我們不使用的「謝謝」,或者「任何幫助表示讚賞」,或簽名(因此)。請參閱「[應該'嗨','謝謝',標語和致敬從帖子中刪除?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be 。-removed - 從 - 個) – 2013-03-27 14:35:10
什麼樣的計時器是? - 沒有命名空間 – 2013-03-27 14:42:09
我插入的文本上方usings,我做這個的System.Threading定時器 – marts 2013-03-27 14:48:32