【问题标题】:Task status always waiting for activation任务状态一直在等待激活
【发布时间】:2013-12-11 02:56:08
【问题描述】:

我正在为我的项目使用这个异步代码:

public async Task<IEnumerable<Area>> GetAreas()
{

        var webclient = new WebClient();
        var result = await webclient.DownloadStringTaskAsync(new Uri(uri)).ConfigureAwait(false);

        return JsonConvert.DeserializeObject<IEnumerable<Area>>(result);
}


public async Task<ActionResult> Index()
    {
        var areas = GetAreas();
        Task.WaitAll(areas);
        return View(model: areas);
    }

我已经尝试过this,但是当我调试我的程序区域变量时,它具有以下属性: 状态:等待激活,方法:“”,结果:“”。 我知道发生这种情况是因为死锁异步。

请帮我解决我的问题。

【问题讨论】:

  • 等待 Task.WhenAll(areas)
  • 我正在使用 .net 4 和 Visual Studio 2010。所以我找不到那个方法。谢谢
  • 我找到了this,但我很困惑如何在我的代码中实现它。我试过了,同样的问题发生了。

标签: c# asynchronous asp.net-web-api


【解决方案1】:

这个怎么样:

public Task<ActionResult> Index()
{
    var tcs = new TaskCompletionSource<ActionResult>();
    GetAreas().ContinueWith(t => 
    {
      if(t.IsCancelled)
        tcs.SetCancelled();
      else if(t.IsFaulted)
        tcs.SetException(t.Exception);
      else
        tcs.SetResult(new View(model: t.Result); 
    });
    return tcs.Task;
}

【讨论】:

  • 我试过了。我也有同样的问题。当我调试我的代码时。 tcs.Task.Status 仍然是“WaitingforActivation”。谢谢
猜你喜欢
  • 2016-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
  • 1970-01-01
  • 2014-06-08
  • 1970-01-01
相关资源
最近更新 更多