title: C# - Encode video with Azure Media Services asynchronously and handle task complete
body: <p>I have an ASP.NET MVC web application and I want to encode a video using Azure Media Services. </p>
  
  <p>Since this process lasts too long, I need to <strong>run it asynchronously</strong> so I don't keep the user waiting for this action to be processed. Also, I need to somehow <strong>handle the execution of this task, as soon as it ends</strong>.</p>
  
  <p><strong>Azure Media Services documentation</strong> provides a code skeleton for implementing this:</p>
  
  <pre><code>static public IAsset EncodeToAdaptiveBitrateMP4Set(IAsset asset)
  {
      // Declare a new job.
      IJob job = _context.Jobs.Create("Media Encoder Standard Job");
      // Get a media processor reference, and pass to it the name of the 
      // processor to use for the specific task.
      IMediaProcessor processor = GetLatestMediaProcessorByName("Media Encoder Standard");
  
      // Create a task with the encoding details, using a string preset.
      // In this case "Adaptive Streaming" preset is used.
      ITask task = job.Tasks.AddNew("My encoding task",
          processor,
          "Adaptive Streaming",
          TaskOptions.None);
  
      // Specify the input asset to be encoded.
      task.InputAssets.Add(asset);
      // Add an output asset to contain the results of the job. 
      // This output is specified as AssetCreationOptions.None, which 
      // means the output asset is not encrypted. 
      task.OutputAssets.AddNew("Output asset",
          AssetCreationOptions.None);
  
      job.StateChanged += new EventHandler&lt;JobStateChangedEventArgs&gt;(JobStateChanged);
      job.Submit();
      job.GetExecutionProgressTask(CancellationToken.None).Wait();
  
      return job.OutputMediaAssets[0];
  }
  
  private static void JobStateChanged(object sender, JobStateChangedEventArgs e)
  {
      // do something when job state changes 
  }
  </code></pre>
  
  <p>This code does the job of encoding the video in Azure Media Services, but the processing is done synchronously, so the user is blocked until this action ends.</p>
  
  <p>Instead of this instruction that makes the program wait for the task to end:</p>
  
  <pre><code>job.GetExecutionProgressTask(CancellationToken.None).Wait();
  </code></pre>
  
  <p>, I need something to make the job run async in Azure Media Services, and to be able to handle the end of the task (run a certain code when the encoding ends).</p>
  
  <p>Can you help me with this? If you need more info, please give a shout! </p>