How can I use a method async Task and return string, and then how do I pass a delegate for that method to a constructor and use it later?

前端 未结 4 565
滥情空心
滥情空心 2021-01-20 15:05

I have this method that returns string:

public string SendResponse(HttpListenerRequest request)
{
    string result = \"\";
    string key = req         


        
4条回答
  •  野性不改
    2021-01-20 15:27

    The question if it's possible to make the SendResponse to return string since i need it and also to use the await ?

    Async is "all the way". It means that once you start using await in your code, your method signature propagates upwards, going through your entire call-stack. This means that any async method in your code has to return either a Task or a Task and have the async modifier added to it, in-order for the compiler to detect that this is an async-method and needs to be transformed into a state-machine.

    What this means is that this synchronous signature:

    public string SendResponse(HttpListenerRequest request)
    

    Needs to turn into an asynchronous signature:

    public async Task SendResponseAync(HttpListenerRequest request)
    

    There is an option of synchronously blocking on your code using Task.Result. I would not recommend it, as you shouldn't block on async code. This leads to nothing more than trouble (usually deadlocks).

提交回复
热议问题