C# Get Request (API) - 如何回调? (代表?)

C# Get Request (API) - How to Callback? (Delegate?)

我认为对于我想做的事情,我需要某种callback/delegate。现在我花了大约 8 个小时阅读有关这些回调的内容并观看了一些 youtube 视频,但我仍然不完全理解它们是如何工作的。 (到目前为止,任何语言都使用了较新的回调。)

单击按钮时调用函数:

private void btnLoad_Click(object sender, EventArgs e)
{
    GetRequest("http://192.168.68.127/axis-cgi/param.cgi?action=list&group=MediaClip", "root", "root");
}

这是用于获取请求结果的函数:

public static async void GetRequest(string url, string user, string pass)
{
    using (HttpClientHandler handler = new HttpClientHandler { Credentials = new System.Net.NetworkCredential(user, pass) })
    {
        using (HttpClient client = new HttpClient(handler))
        {
            using (HttpResponseMessage response = await client.GetAsync(url))
            {
                using (HttpContent content = response.Content)
                {
                        string mycontent = await content.ReadAsStringAsync();

                        // --- Do different stuff with "mycontent", depending which button was clicked ---
                        // --- Insert function here ?! ---
                }
            }
        }
    }
}

现在我的问题是,如何告诉"GetRequest(string url, string user, string pass)"在我需要的地方执行特定的功能? 我想我需要某事。喜欢:

GetRequest(string url, string user, string pass, function())

使用 async-await 你不需要使用 "callbacks"

将您的方法更改为 return "awaitable" 内容。

public static async Task<string> GetRequest(string url, 
                                            string user, 
                                            string pass)
{
    var credentials = new System.Net.NetworkCredential(user, pass);
    using (var handler = new HttpClientHandler { Credentials = credentials })
    {
        using (var client = new HttpClient(handler))
        {
            using (var response = await client.GetAsync(url))
            {
                using (HttpContent content = response.Content)
                {
                    return await content.ReadAsStringAsync();
                }
            }
        }
    }        
}

注意return方法的类型Task<string>

然后随心所欲地使用它

string content = await GetRequest("url", "admin", "admin");
// Do staff with content
  1. 定义一个delegate,定义方法的签名
    属于delegate。在这种情况下:return 值 void 而没有
    参数:

public delegate void YourDelegate();

  1. 定义应该用于 GetRequest 的回调函数:

public void CallbackFunction() {...}

  1. GetRequest方法中定义一个参数来使用回调函数:

public void GetRequest(string url, string user, string pass, YourDelegate callback) {...}

  1. 调用GetRequest中的回调:

callback.Invoke();

  1. 执行示例GetRequest:

GetRequest("http://192.168.68.127/axis-cgi/param.cgi?action=list&group=MediaClip", "root", "root", CallbackFunction);