2013-03-27 61 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

相关问题