Is async recursion safe in C# (async ctp/.net 4.5)?

后端 未结 1 1233
醉话见心
醉话见心 2021-02-07 01:56

In C# with async ctp or the vs.net 2011 beta we can write recursive code like this:

public async void AwaitSocket()
{
    var socket = await this.AcceptSocketAsy         


        
1条回答
  •  北恋
    北恋 (楼主)
    2021-02-07 02:40

    From the discussion above, I guess something like this will be the best approach. Please give feedback

    public async void StartAcceptingSockets()
    {
        await Task.Yield(); 
        // return to caller so caller can start up other processes/agents
        // TaskEx.Yield in async ctp , Task.Yield in .net 4.5 beta
    
        while(true)
        {
            var socket = await this.AcceptSocketAsync();
            HandleAsync(socket); 
            //make handle call await Task.Yield to ensure the next socket is accepted as fast 
            //as possible and dont wait for the first socket to be completely handled
        } 
    }
    
    private async void HandleAsync(Socket socket)
    {
          await Task.Yield(); // return to caller
    
          ... consume the socket here...
    }
    

    0 讨论(0)
提交回复
热议问题