I think your problem arises from the way linq expressions are executed when they are called, and not from where they are declared.
So your statement:
var traceJob = from jobDefinition in service.JobDefinitions where jobDefinition.Id == traceGuid select jobDefinition;
This is roughly functionally equivalent:
IEnumerable<JobDefinition> GetJobDefinitions(YourService service, Guid traceGuid) { foreach(var jobDefinition in service.JobDefinitions) if(jobDefinition.Id == traceGuid) yield return jobDefinition; }
Therefore, when you call traceJob.Count() , you make the equivalent of calling GetJobDefinitions(service, traceGuid).Count() , and each time you call traceJob.First() , you call the loop again.
This is probably not a problem if service.JobDefinitions can be called again and again. However, if the results change over time (for example, if tasks are added at runtime), or if subsequent runs have different results, you will have problems.
In any case, you might be better off executing the loop only once:
var traceJobs = from jobDefinition in service.JobDefinitions where jobDefinition.Id == traceGuid select jobDefinition; // This is where the loop above actually executes - if it empty it will return null var firstJob = traceJobs.FirstorDefault(); if(firstJob != null) { firstJob.RunNow(); Console.WriteLine(firstJob.DisplayName + " Last Run Time: " + firstJob.LastRunTime); }
Alternatively, you can force the loop to execute by converting it to a list or array:
var traceJobsExecuted = traceJobs.ToList();
Keith source share