这些方法运行在哪个线程?

时间:2013-03-27 14:32:00

标签: c# multithreading timer

我想要一个能够在与其父级分开的线程中执行定时任务的类,但是我有点混淆了各个部分所属的线程,任何信息都会受到赞赏。

我的目的是使定时任务独立于父项运行,因为父项包装对象将控制其中多项。

这就是我提出的:

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

2 个答案:

答案 0 :(得分:3)

看起来你正在使用System.Threading.Timer。如果是这样,tick方法在池线程上运行。最确定的是不是应用程序的主线程。

仅为了您的信息,Windows窗体计时器在GUI线程上执行已发生的事件。

System.Timers.Timer的默认行为是在池线程上执行Elapsed事件。但是,如果将SynchronizingObject设置为引用Windows窗体组件,则该事件将被封送到GUI线程。

答案 1 :(得分:0)

来自http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx

“该方法不会在创建计时器的线程上执行;它会在系统提供的ThreadPool线程上执行。”

相关问题