2013-03-27 35 views
0

我想一類是能夠在一個線程中分離出來,從它的父執行定時任務,但我有點糊塗了哪個線程的各個部分屬於任何信息,將不勝感激。哪個線程執行方法?

我的目的是使定時任務從父獨立運作,因爲將這些由家長包裝對象控制一個以上。

這是我想出了:

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; 
     } 
    } 
} 
+0

不同於論壇的網站,我們不使用的「謝謝」,或者「任何幫助表示讚賞」,或簽名(因此)。請參閱「[應該'嗨','謝謝',標語和致敬從帖子中刪除?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be 。-removed - 從 - 個) – 2013-03-27 14:35:10

+0

什麼樣的計時器是? - 沒有命名空間 – 2013-03-27 14:42:09

+0

我插入的文本上方usings,我做這個的System.Threading定時器 – marts 2013-03-27 14:48:32

回答

3

它看起來像你使用System.Threading.Timer。如果是這樣,則tick方法在池線程上運行。這是最確定的而不是該應用程序的主線程。

只是爲了您的信息,Windows窗體計時器執行GUI線程所經過的事件。

System.Timers.Timer的默認行爲是在池線程上執行Elapsed事件。但是,如果您將SynchronizingObject設置爲引用Windows窗體組件,則該事件將封送到GUI線程。

+0

因此,這將意味着我可以消除穿線整個過程的一部分,以及鎖定(除非打勾訪問可以從外部訪問的字段)。讓計時器運行而不用專門設置線程來進行計時操作。這將簡化代碼很多:) – marts 2013-03-27 14:54:56

+1

此外,沒有必要在新線程中創建計時器。另外最好使用ManualResetEvent來阻塞,直到中止。最後,最好實現IDisposable接口並調用timer.Dispose在其Dispose方法中。 – 2013-03-27 14:57:10

+0

基於這些評論,我認爲這是最終的玩法:...增加主要問題,因爲太長了! – marts 2013-03-27 15:26:39

相關問題