Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Services are run by the windows service hosting system, which runs using MTA threads. You can't control this. You have to create a new <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.aspx" rel="noreferrer">Thread</a> and <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.setapartmentstate.aspx" rel="noreferrer">set its ApartmentState to STA</a>, and do your work on this thread.</p> <p>Here's a class that extends ServiceBase that does this:</p> <pre><code>public partial class Service1 : ServiceBase { private System.Timers.Timer timer; public Service1() { InitializeComponent(); timer = new System.Timers.Timer(); this.timer.Interval = 10000; // set for 10 seconds this.timer.Elapsed += new System.Timers.ElapsedEventHandler(Tick); } protected override void OnStart(string[] args) { timer.Start(); } private void Tick(object sender, ElapsedEventArgs e) { // create a thread, give it the worker, let it go // is collected when done (not IDisposable) var thread = new Thread(WorkerMethod); thread.SetApartmentState(ApartmentState.STA); thread.Start(); OnStop(); // kill the timer } private void WorkerMethod(object state) { // do your work here in an STA thread } protected override void OnStop() { timer.Stop(); timer.Dispose(); } } </code></pre> <p>Note this code doesn't actually stop the service, it stops the timer. There could be lots of work still being done on multiple threads. For instance, if your work consisted of running multiple queries off a large database you may end up crashing because you have too many threads running at the same time.</p> <p>In a situation like this, I'd create a set number of STA threads (maybe 2x the number of cores to start off with) which monitor a thread-safe queue for work items. The timer tick event would be responsible for loading that queue with the work needing done. </p> <p>It all depends on what you're actually doing every ten seconds, whether or not it should be completed the next time the timer ticks, what you should do in this situation, etc etc.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload