Closed nvchernov closed 2 years ago
Currently in your foreach
loop, you are re-registering the task with RegisterTaskDefinition
and then you are registering it again with RegisterChanges
and then stopping the task that may have just started running after registration and then registering it again after disabling, which also registers the task.
Also, instead of x.Definition.Triggers.Any(x => x.TriggerType == TaskTriggerType.Idle)
you can use x.Definition.Triggers.ContainsType(typeof(IdleTrigger))
. It is a little faster.
Also, to change a trigger, you have to copy it, remove it and re-add it. Yes, that is unintuitive, but it is a design flaw in Microsoft's libraries that I haven't been able to work around.
I would rewrite as:
public string[] DisableIdleTriggerTasks()
{
var tasks = TaskService.Instance.AllTasks;
var idleTriggerTasks = tasks
.Where(x => x.Definition.Triggers.ContainsType(typeof(IdleTrigger)) && x.State != TaskState.Disabled)
.ToArray();
foreach (var task in idleTriggerTasks)
{
var chg = false;
for (int i = task.Definition.Triggers.Count - 1; i >= 0; i--)
{
var tr = task.Definition.Triggers[i];
if (tr.TriggerType == TaskTriggerType.Idle)
{
task.Definition.Triggers.RemoveAt(i);
tr.Enabled = false;
task.Definition.Triggers.Add(tr);
chg = true;
}
}
if (chg)
task.RegisterChanges(); // Let me know if this throws an exception
task.Enabled = false;
}
return tasks.Select(x => $"* [{x.Name}] [{x.Path}]").ToArray();
}
@dahall it works, thank you very much!
Hi, I trying to update some windows tasks, and a I got this exception
Code, where I getting exception