我有一个名为TapApiService
的WCF服务,其中包含以下方法:
public class TapApiService : Contracts.ServiceContracts.ITapApiService
{
private static readonly IConfigurationManagerWrapper ConfigWrapper = new ConfigurationManagerWrapper();
private static UriManager uriManager = new UriManager(ConfigWrapper.AppSettings["tapScheme"], ConfigWrapper.AppSettings["tapHost"], ConfigWrapper);
public JobLongForm GetJob(string jobId)
{
var request = uriManager.GetUriFromKey("jobResource", jobId).ToString().GetTapRequest("GET", ConfigWrapper);
return JsonConvert.DeserializeObject<JobLongForm>(request.GetResponseString());
}
public IEnumerable<string> GetAllJobIds()
{
return GetAllJobs().Select(job => job.Id);
}
public IEnumerable<JobShortForm> GetAllJobs()
{
var request = uriManager.GetUriFromKey("allJobsResource").ToString().GetTapRequest("GET", ConfigWrapper);
return JsonConvert.DeserializeObject<JobShortForm[]>(request.GetResponseString());
}
public IEnumerable<JobLongForm> GetFullJobs(IEnumerable<string> jobIds)
{
return jobIds.Select(GetJob);
}
}
我有一个我正在测试的控制台应用程序。它具有以下代码: var proxy = new TapApiService();
var stopwatch = new Stopwatch();
stopwatch.Start();
var ids = proxy.GetAllJobIds();
proxy.GetFullJobs(ids);
stopwatch.Stop();
Console.WriteLine(stopwatch.GetElapsedTimeString());
stopwatch.Reset();
stopwatch.Start();
proxy.GetAllJobIds().AsParallel().Select(id => proxy.GetJob(id));
stopwatch.Stop();
Console.WriteLine(stopwatch.GetElapsedTimeString());
结果是:00:00:00.713
和00:00:00.104
AsParallel()
实施显然要快得多。但是,如果我将AsParallel()
移动到GetFullJobs(IEnumerable<string> jobIds)
方法内部,就像这样:
public IEnumerable<JobLongForm> GetFullJobs(IEnumerable<string> jobIds)
{
return jobIds.AsParallel().Select(GetJob);
}
我得到00:00:00.813
和00:00:00.158
。第二个实现仍然更快。我认为他们的表现现在会一样。我在这里缺少什么?