Я вставлю то, что сработало для меня:
HtmlLink link = new HtmlLink();
//Add appropriate attributes
link.Attributes.Add("rel", "stylesheet");
link.Attributes.Add("type", "text/css");
link.Href = "/Resources/CSS/NewStyles.css";
link.Attributes.Add("media", "screen, projection");
//add it to page head section
this.Page.Header.Controls.Add(link);
Даже если я много искал по этому вопросу, я бы добавил переписывающуюся таблицу стилей при нажатии кнопки. Я использовал приведенный выше код, и он отлично сработал для меня.
Из MSDN :
«Не используйте конструктор для выполнения обработки, которая должна быть в OnStart. Используйте OnStart для обработки всей инициализации вашей службы. Конструктор вызывается при запуске исполняемого файла приложения, а не при запуске службы. Исполняемый файл запускается до OnStart. Когда вы продолжаете например, конструктор не вызывается снова, потому что SCM уже удерживает объект в памяти. Если OnStop освобождает ресурсы, выделенные в конструкторе, а не в OnStart, необходимые ресурсы не будут созданы снова при втором вызове службы ».
Если ваш таймер не инициализирован при вызове OnStart, это может быть проблемой.
Я бы также проверил тип таймера, убедитесь, что это System.Timers.Timer for Services. Здесь - пример того, как настроить таймер в службе Windows.
// TODONT: Используйте службу Windows только для запуска запланированного процесса
Я попробовал ваш код, и он кажется нормальным . Единственное отличие, которое у меня было, заключалось в жестком кодировании значения таймера (Service1.cs). Сообщите мне, если приведенное ниже не работает.
Service1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Threading;
namespace WindowsServiceTest
{
public partial class Service1 : ServiceBase
{
private System.Timers.Timer timer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//instantiate timer
Thread t = new Thread(new ThreadStart(this.InitTimer));
t.Start();
}
protected override void OnStop()
{
timer.Enabled = false;
}
private void InitTimer()
{
timer = new System.Timers.Timer();
//wire up the timer event
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
//set timer interval
//var timeInSeconds = Convert.ToInt32(ConfigurationManager.AppSettings["TimerIntervalInSeconds"]);
double timeInSeconds = 3.0;
timer.Interval = (timeInSeconds * 1000);
// timer.Interval is in milliseconds, so times above by 1000
timer.Enabled = true;
}
protected void timer_Elapsed(object sender, ElapsedEventArgs e)
{
int timer_fired = 0;
}
}
}
Service1.Designer.cs
namespace WindowsServiceTest
{
partial class Service1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
this.CanPauseAndContinue = true;
}
#endregion
}
}
Я только что создал пустой проект службы Windows и добавил ниже, чтобы я мог запустить installutil.exe и присоединиться к вышеупомянутому чтобы узнать, сработало ли событие (и оно произошло).
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.ServiceProcess;
namespace WindowsServiceTest
{
[RunInstaller(true)]
public class MyServiceInstaller : System.Configuration.Install.Installer
{
public MyServiceInstaller()
{
ServiceProcessInstaller process = new ServiceProcessInstaller();
process.Account = ServiceAccount.LocalSystem;
ServiceInstaller serviceAdmin = new ServiceInstaller();
serviceAdmin.StartType = ServiceStartMode.Manual;
serviceAdmin.ServiceName = "Service1";
serviceAdmin.DisplayName = "Service1 Display Name";
Installers.Add(process);
Installers.Add(serviceAdmin);
}
}
}