我发现对于昂贵的 IO 绑定操作,我可以使用TaskCompletionSource
如此处所示http://msdn.microsoft.com/en-us/library/hh873177.aspx#workloads
但是显示的示例只是等待一段时间并返回 DateTime。
public static Task<DateTimeOffset> Delay(int millisecondsTimeout)
{
 TaskCompletionSource<DateTimeOffset> tcs = null;
 Timer timer = null;
 timer = new Timer(delegate
 {
    timer.Dispose();
    tcs.TrySetResult(DateTimeOffset.UtcNow);
 }, null, Timeout.Infinite, Timeout.Infinite);
 tcs = new TaskCompletionSource<DateTimeOffset>(timer);
 timer.Change(millisecondsTimeout, Timeout.Infinite);
 return tcs.Task;
}
上面的代码等待超时。我有一个数据库调用,我想以上述方式触发,但对如何编写它有点困惑:
   using (var context = new srdb_sr2_context())
   {
      return context.GetData("100", "a2acfid");
   }
我编写了如下函数,但不确定这是否是正确的方法:
TaskCompletionSource<IList<InstructorsOut>> tcs = null;
        Timer timer = null;
        timer = new Timer(delegate
        {
            timer.Dispose();
            //prepare for expensive data call
            using (var context = new srdb_sr2_context())
            {
                var output = context.GetData("100", "a2acfid");
                //set the result
                tcs.TrySetResult(output);
            }  
        }, null, Timeout.Infinite, Timeout.Infinite);
        tcs = new TaskCompletionSource<IList<InstructorsOut>>(timer);
        timer.Change(0, Timeout.Infinite);
        return tcs.Task;
任何帮助,将不胜感激。