c# - 如何轻松地将两个异步请求链接在一起?

标签 c# .net multithreading asynchronous iasyncresult

2013 编辑: asyncawait现在让这变得微不足道! :-)


我有一些代码可以对网站进行屏幕抓取(仅用于说明目的!)

    public System.Drawing.Image GetDilbert()
    {
        var dilbertUrl = new Uri(@"http://dilbert.com");
        var request = WebRequest.CreateDefault(dilbertUrl);
        string html;
        using (var webResponse = request.GetResponse())
        using (var receiveStream = webResponse.GetResponseStream())
        using (var readStream = new StreamReader(receiveStream, Encoding.UTF8))
            html = readStream.ReadToEnd();

        var regex = new Regex(@"dyn/str_strip/[0-9/]+/[0-9]*\.strip\.gif");
        var match = regex.Match(html);
        if (!match.Success) return null;
        string s = match.Value;
        var groups = match.Groups;
        if (groups.Count > 0)
            s = groups[groups.Count - 1].ToString();    // the last group is the one we care about

        var imageUrl = new Uri(dilbertUrl, s);
        var imageRequest = WebRequest.CreateDefault(imageUrl);
        using (var imageResponse = imageRequest.GetResponse())
        using (var imageStream = imageResponse.GetResponseStream())
        {
            System.Drawing.Image image_ = System.Drawing.Image.FromStream(imageStream, true /*useEmbeddedColorManagement*/, true /*validateImageData*/);
            return (System.Drawing.Image)image_.Clone(); // "You must keep the stream open for the lifetime of the Image."
        }
    }

现在,我想异步调用 GetDilbert()。使用委托(delegate)的简单方法:

    Func<System.Drawing.Image> getDilbert;
    IAsyncResult BeginGetDilbert(AsyncCallback callback, object state)
    {
        getDilbert = GetDilbert;
        return getDilbert.BeginInvoke(callback, state);
    }
    System.Drawing.Image EndGetDilbert(IAsyncResult result)
    {
        return getDilbert.EndInvoke(result);
    }

虽然这确实有效,但效率不高,因为委托(delegate)线程将花费大部分时间等待两个 I/O 操作。

我想做的是调用request.BeginGetResponse() ,进行正则表达式匹配,然后调用 imageRequest.BeginGetResponse() .同时使用标准异步调用模式并保留 BeginGetDilbert()EndGetDilbert() 的签名。

我尝试了几种方法,但对其中任何一种都不完全满意;这似乎是一种皇家痛苦。因此,问题。 :-)


编辑:似乎使用迭代器的方法是 frowned on by the C# compiler team .

A plea from the compiler team:

Though it is assuredly the case that you CAN use iterators to implement state machines, poor-mans coroutines, and so on, I wish people would not do so.

Please use tools for the purposes for which they were intended. If you want to write state machines, write yourself a library that is designed specifically to solve that general problem and then use it.

Using tools for purposes other than what they were intended for is "clever", and clever is bad; clever is hard for maintenance programemrs to understand, clever is hard to extend, clever is hard to reason about, clever makes people think "out of the box"; there's good stuff in that box.


使用 Future<>回答是因为它保留在 C# 中,这与我的示例代码相同。不幸的是,TPL 和 F# 都没有得到 Microsoft 的官方支持……但是。

最佳答案

要做到这一点有点像一场噩梦。您需要创建回调以传递到每个“开始”方法,然后运行该方法的“延续”。 (并且不要忘记确保所有异常处理和 CompletedSynchronously 逻辑都是正确的!)当您今天在 C# 中编写此代码时,您的代码变成了一团毫无希望的意大利面条,但这是您实现目标的唯一方法(没有线程阻塞 I/O 等待)。

另一方面,如果符合您的情况,F#使得这对于正确创作非常简单和直接。参见 this video (即,从 52:20 开始的 8 分钟)概要。

编辑

为了回答 Dan 的评论,这里有一个非常粗略的草图……我从我在 Outlook 中写的一封电子邮件中提取了它,我怀疑它能否编译。异常路径总是很粗糙,所以要小心(如果“cb”抛出怎么办?);你可能想在某个地方用 C# 找到一个坚如磐石的 AR/Begin/End 实现(我不知道在哪里,我敢肯定肯定有很多)并将其用作模型,但这显示了要点。问题是,一旦你创作了一次,你就永远拥有它; BeginRun 和 EndRun 作为任何 F# 异步对象的“开始/结束”。我们在 F# 错误数据库中建议在 F# 库的 future 版本中在异步之上公开 Begin/End APM,以便更轻松地从传统 C# 代码中使用 F# 异步计算。 (当然,我们也在努力更好地使用 .Net 4.0 中并行任务库中的“任务”。)

type AR<’a>(o,mre,result) =
    member x.Data = result
    interface IAsyncResult with
        member x.AsyncState = o
        member x.AsyncWaitHandle = mre
        member x.CompletedSynchronously = false
        member x.IsCompleted = mre.IsSignalled

let BeginRun(a : Async<’a>, cb : AsyncCallback, o : obj) =
    let mre = new ManualResetEvent(false)
    let result = ref None
    let iar = new AR(o,mre,result) :> IAsyncResult
    let a2 = async { 
        try
            let! r = a
            result := Choice2_1(r)
        with e ->
            result := Choice2_2(e)
            mre.Signal()
            if cb <> null then 
                cb.Invoke(iar)
            return () 
    }
    Async.Spawn(a2)
    iar

let EndRun<’a>(iar) =
    match iar with
    | :? AR<’a> as ar -> 
        iar.AsyncWaitHandle.WaitOne()
        match !(ar.Data) with
        | Choice2_1(r) -> r
        | Choice2_2(e) -> raise e

关于c# - 如何轻松地将两个异步请求链接在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/660776/

相关文章:

c# - 从控制台 C# 上的位置读取

c# - System.Net.Http.HttpClient 实例在设置逗号时抛出异常。为什么?

c# - 任何人都可以推荐使用 C# 发送和接收 SMS 的任何基于英国的优秀 SMS 网关吗?

.net - 无法使用 .net 远程处理

Java,多个线程一次只执行一个

c# - 读取csv文件c#

c# - 在哪些情况下我需要为 IEnumerable 和 IQueryable 创建两种不同的扩展方法?

c# - 部署 autocad .net dll

c# - 你如何获得 C# 中正在运行的线程列表?

android - 是什么导致 Looper.Loop() 挂起(即永不返回)