我认为对于我想做的事情,我需要某种回调/委托。现在花大约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(字符串url,字符串用户,字符串传递)"在我需要的地方执行特定的功能? 我想我需要......像:
GetRequest(string url, string user, string pass, function())
答案 0 :(得分:2)
使用async-await
,您不需要使用"回调"
更改您的方法以返回"等待"内容。
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();
}
}
}
}
}
注意方法Task<string>
然后在任何地方使用它
string content = await GetRequest("url", "admin", "admin");
// Do staff with content
答案 1 :(得分:1)
delegate
,定义方法的签名delegate
。在这种情况下:返回值void
而不是
参数: public delegate void YourDelegate();
GetRequest
的回调函数: public void CallbackFunction() {...}
GetRequest
方法中定义参数以使用回调函数: public void GetRequest(string url, string user, string pass, YourDelegate callback) {...}
GetRequest
: callback.Invoke()
;
GetRequest
的示例: GetRequest("http://192.168.68.127/axis-cgi/param.cgi?action=list&group=MediaClip", "root", "root", CallbackFunction);