Поскольку HttpContext привязан к текущему запросу, после его возврата он больше не будет доступен. Но ваша асинхронная задача продолжает выполняться в фоновом режиме, и когда она пытается получить к ней доступ, она больше не доступна. По этой причине вы должны передать все зависимости задаче в качестве параметра:
public ActionResult Contact()
{
// everything that depends on an HttpContext should be done here and passed
// as argument to the task
string p = HttpContext.Server.MapPath("~/test.txt");
// Create an asynchronous processing operations
Task task = new Task(state =>
{
var path = (string)state;
var testTexts = new[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
foreach (string text in testTexts)
{
System.IO.File.AppendAllText(path, text);
// Thread to hang five seconds to simulate asynchronous time difference
Thread.Sleep(5000);
}
}, p);
// Asynchronous processing
task.Start();
return View();
}