我正在编写一个类,它利用USING
语句连接到服务器上的任务调度程序并“做事”;比如启用/禁用任务、启动和停止等。我想改进代码重用,也许通过使用委托,但我不知道如何去做。这是我当前的一些代码:
private static void StopRunningTask(string taskName, string hostName)
{
Regex regex = GetRegexForFindTask(taskName);
using (TaskService ts = new TaskService(hostName))
{
foreach (Task t in ts.FindAllTasks(regex, true))
{
if (t.Name.Equals(taskName, StringComparison.OrdinalIgnoreCase) && t.State == TaskState.Running)
t.Stop();
}
}
private static void RunTask(string taskName, string hostName)
{
Regex regex = GetRegexForFindTask(taskName);
using (TaskService ts = new TaskService(hostName))
{
foreach (Task t in ts.FindAllTasks(regex, true))
{
if (t.Name.Equals(taskName, StringComparison.OrdinalIgnoreCase) && t.State == TaskState.Ready)
t.Run();
}
}
private static void ChangeTaskEnabledState(string taskName, bool enabled, string hostName)
{
Regex regex = GetRegexForFindTask(taskName);
using (TaskService ts = new TaskService(hostName))
{
foreach (Task t in ts.FindAllTasks(regex, true))
{
if (t.Name.Equals(taskName, StringComparison.OrdinalIgnoreCase))
t.Enabled = enabled;
}
}
private static Regex GetRegexForFindTask(string taskName)
{
var regex = new Regex(string.Format(@"{0}", taskName), RegexOptions.IgnoreCase);
return regex;
}