0

我正在编写一些代码,我希望在控制台应用程序中具有三个主要功能,包括 .NET 6 和 VS2022

  • 计时器应处理发票
  • 侦听器应侦听传入的 http 请求
  • “r”键应该处理发票

计时器在网络服务器启动之前启动,并且工作正常。(不包括在内)问题是计时器每天只运行几次,我希望能够使用控制台中的键触发发票流程。(所以如果用户输入即“r”键发票“方法”应该运行

运行以下代码将在我点击“r”时触发 invoice 方法,但侦听器未在侦听,因为它正在等待输入键。有没有办法同时“等待钥匙”和“听”?

我试图启用“WaitOne”行并将“结果”行移到循环内,但我无法让它工作。

我正在使用从该站点获得的一些代码

public async Task StartWebserverAsync2() {

    HttpListener Listener = new HttpListener();

    string[] prefixes = { "https://*:8443/" };
    foreach (string s in prefixes) {
        Listener.Prefixes.Add(s);
    }

    Listener.Start();
    IAsyncResult result = Listener.BeginGetContext(new AsyncCallback(ListenerCallback), Listener);

    while (Listener.IsListening) {

        String line = Console.ReadLine();
        Log.Information(line);
        if (line == "r") {
            await new InvoiceHandler().CheckForNewInvoicesAsync();
        }

        // Applications can do some work here while waiting for the
        // request. If no work can be done until you have processed a request,
        // use a wait handle to prevent this thread from terminating
        // while the asynchronous operation completes.
        // Console.WriteLine("Waiting for request to be processed asyncronously.");
        //  result.AsyncWaitHandle.WaitOne();
        //  Console.WriteLine("Request processed asyncronously.");


    }
    Log.Information("Not listening");
}

public static void ListenerCallback(IAsyncResult result) {
    HttpListener listener = (HttpListener)result.AsyncState;
    // Call EndGetContext to complete the asynchronous operation.
    HttpListenerContext context = listener.EndGetContext(result);
    HttpListenerRequest request = context.Request;
    // Obtain a response object.
    HttpListenerResponse response = context.Response;
    // Construct a response.
    string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
    // Get a response stream and write the response to it.
    response.ContentLength64 = buffer.Length;
    System.IO.Stream output = response.OutputStream;
    output.Write(buffer, 0, buffer.Length);
    // You must close the output stream.
    output.Close();
}
4

0 回答 0