endMethod从未在TaskFactory <t> .FromAsync()</t>中调用

时间:2013-05-20 15:23:29

标签: .net wcf silverlight task-parallel-library async-await

我有以下Silverlight代码。

Container container = new Container("http://localhost:8080/odata");
DataServiceQuery dsq = container.MyEntity;
IEnumerable result = Task<IEnumerable>.Factory.FromAsync(dsq.BeginExecute, dsq.EndExecute, null).Result;

我遇到的问题是永远不会调用dsq.EndExecute。我在Fiddler中观看了HTTP流量,并且http://localhost:8080/odata/MyEntity的请求消失了,接收到了以下响应。该任务似乎并未承认已收到回复。

HTTP/1.1 200 OK
Server: ASP.NET Development Server/11.0.0.0
Date: Mon, 20 May 2013 15:04:16 GMT
X-AspNet-Version: 4.0.30319
DataServiceVersion: 3.0
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: application/atom+xml; charset=utf-8
Content-Length: 562
Connection: Close

<?xml version="1.0" encoding="utf-8"?>
<feed xml:base="http://localhost:8080/odata/" xmlns="http://www.w3.org/2005/Atom" 
    xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" 
    xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" 
    xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml">
  <id>http://schemas.datacontract.org/2004/07/</id>
  <title />
  <updated>2013-05-20T15:04:16Z</updated>
  <link rel="self" href="http://localhost:8080/odata/MyEntity" />
  <author>
    <name />
  </author>
</feed>

我做错了吗?

3 个答案:

答案 0 :(得分:1)

请勿致电Result。你应该await结果。在许多情况下,Result将使GUI应用程序死锁(包括Silverlight)。

我更充分地解释了这个死锁on my blogin an MSDN article

答案 1 :(得分:1)

我通过一起避免FromAsync()来解决这个问题。以下代码适用于我。

var result = Task.Factory.StartNew(() => dsq.BeginExecute(null, null))
    .ContinueWith(t => dsq.EndExecute(t.Result)).Result;

答案 2 :(得分:0)

您是否尝试过添加async / await?

public async void foo()
{
   IEnumerable result = await Task<IEnumerable>.Factory.FromAsync(
      dsq.BeginExecute, dsq.EndExecute, null);
}