如何做到在F#中链接的回调? [英] How to do chained callbacks in F#?

查看:249
本文介绍了如何做到在F#中链接的回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我使用的TcpListener / TcpClient的异步版本,而我这些链接通过回调方法,以便另一个接受/回调完成读取时发布。下面是一个例子(未经测试):

In C# I am using the asynchronous versions of TcpListener/TcpClient, and I am chaining these via the callback method so that another Accept/Read is posted when the callback completes. Here is an example (untested):

    public void Start()
    {
        TcpListener listener = new TcpListener(IPAddress.Any, 3000);
        listener.Start();

        PostAccept(listener);
    }

    private void PostAccept(TcpListener listener)
    {
        listener.BeginAcceptTcpClient(AcceptCallback, listener);
    }

    private void AcceptCallback(IAsyncResult ar)
    {
        var listener = ar.AsyncState as TcpListener;

        if (listener == null)
        {
            return;
        }

        // get the TcpClient and begin a read chain in a similar manner

        PostAccept(listener);
    }

我的问题是我怎么在模型F#类似的东西?我会用async关键字?是BeginAcceptTcpClient,的BeginRead,等以后code ..基本上是code,将在回调函数来执行?例如,这是正确的?

My question is how do I model something similar in F#? Would I use the async keyword? Is the code after BeginAcceptTcpClient, BeginRead, etc.. essentially the code that would be executed in the callback function? For example, is this correct?

let accept(listener:TcpListener) = async {      
  let! client = listener.AsyncAcceptTcpClient()    
  // do something with the TcpClient such as beginning a Read chain
  accept(listener)
  return()
}

因为它不是一个递归方法

以上code不起作用,因为接受的是没有定义,并将其标记在技术上递归是不是真的?

The above code doesn't work because accept isn't defined, and marking it recursive technically isn't true as it isn't a recursive method?

推荐答案

我不知道你所说的它不是一个recusive方法的意思;如果从它自己的定义范围内是指一个函数,那么它是一个递归函数。我没有太多的经验与套接字类,但也许这些方针的东西是你在找什么?

I'm not sure what you mean by "it isn't a recusive method"; if you refer to a function from within its own definition, then it is a recursive function. I don't have much experience with the Sockets classes, but perhaps something along these lines is what you're looking for?

let rec accept(t : TcpListener) =
  async {
    let! client = t.AsyncAcceptTcpClient()

    // do some stuff with client here

    do! accept(t)
  }

这篇关于如何做到在F#中链接的回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆