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 528
滥情空心
滥情空心 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:44

    I believe your latest compile errors are due to not providing a lambda with the correct signature to the WebServer class. So you need to either change what you're passing the constructor, or what it expects. With the way you've implemented WebServer, it needs a non-asynchronous method for _responderMethod. Thus trying to make SendResponse() async is counter productive. I would strongly suggest refactoring either WebServer to process responses asynchronously, or go back to making SendResponse() non-async.

    If you'd like to get your code to compile as is you could try something like this:

    var ws = new WebServer(
            request =>
               {
                  var t = SendResponseAsync(request);
                  t.Wait();
                  return t.Result;
               },
            "http://+:8098/");
            ws.Run();
    

    You might also have to wrap the lambda in the correct delegate type like so:

    var ws = new WebServer(
            new Func(request =>
               {
                  var t = SendResponseAsync(request);
                  t.Wait();
                  return t.Result;
               }),
            "http://+:8098/");
            ws.Run();
    

提交回复
热议问题