title: Suggestions to improve Task responsiveness?
body: <p>I have an application which downloads a single file in 4 different segments (each segment is a different long running task) and serializes the progress at periodic intervals. </p>
  
  <p>When the serialize takes place on a 2 core machine the process will block for 3-10 seconds and then complete. Once this blocking behavior has happened the first time it will never happen again. The 2nd to (n) calls to serialize execute immediately without a hitch. It appears that during the first call blocking the framework did some Task/Threading optimization that prevents the blocking behavior form occurring again. </p>
  
  <p>Does anyone have any insight into this optimization and if it is possible to do this type of optimization at initialization to avoid the blocking behavior all together?</p>
  
  <p>Here is some pseudo code to help describe the situation:</p>
  
  <pre><code>class Download
  {
      private DownloadSegment[] _downloadSegments = new DownloadSegment[4];
  
      public void StartDownload()
      {
          for (int i = 0; i &lt; 4; i++)
          {
              _downloadSegments[i] = new DownloadSegment();
              _downloadSegments[i].Start();
          }
      }
  
      public void Serialize()
      {
          try
          {        
              //enter lock so the code does not serilize the progress while 
              //writing new downloaded info at the same time
              foreach(DownloadSegment segment in _downloadSegments)
              {
                  Monitor.Enter(segment.SyncRoot);
              }
  
              //code to serialize the progress
          }
          finally
          {
              foreach (DownloadSegment segment in _downloadSegments)
              {
                  Monitor.Exit(segment.SyncRoot);
              }
          }
  
      }
  }
  
  class DownloadSegment
  {
      public object SyncRoot = new object();
  
      public void Start()
      {
          Task downloadTask = new Task(
              () =&gt;
                  {
                      //download code
                      lock (SyncRoot)
                      {
                          //wirte to disk code
                      }                        
                  },
          new CancellationToken(),
          TaskCreationOptions.LongRunning);
  
          downloadTask.Start(TaskScheduler.Default);
      }
  }
  </code></pre>