title: C# - Wait for Task with return value
body: <p>I want to have a code block, which should be executed with a maximum time limit. If the functions hangs, it should be aborted.
  From <a href="https://stackoverflow.com/questions/7413612/how-to-limit-the-execution-time-of-a-function-in-c-sharp">this question</a> I adapted the following solution:</p>
  <pre><code>public static void ExecuteWithTimeLimit(int timeLimit_milliseconds, Func&lt;bool&gt; codeBlock)
  {
      Task task = Task.Factory.StartNew(() =&gt;
      {
          codeBlock();
      });
  
      task.Wait(timeLimit_milliseconds);
  }
  </code></pre>
  <p>This works as I want it to behave: If the code <code>codeBlock</code> hangs and takes to long, the task is aborted.</p>
  <p>However, I want the <code>Task</code> to have a return value so I can use <code>task.Result</code>. If I implement this into the code, it doesn't work any more.
  In fact, the task is not cancled and the GUI freezes completly.</p>
  <pre><code>public static void ExecuteWithTimeLimit(int timeLimit_milliseconds, Func&lt;bool&gt; codeBlock)
  {
      Task&lt;bool&gt; task = Task&lt;bool&gt;.Factory.StartNew(() =&gt;
      {
          return codeBlock();
      });
  
      task.Wait(timeLimit_milliseconds);
  }
  </code></pre>
  <p><strong>What is the correct way to execute Methods with a return value with a maximum time limit?</strong></p>