将所有代码包装在 Using Webclient 中有什么负面影响吗?
Any negatives of wrapping all code inside Using Webclient?
using (WebClient client= new WebClient())
{
//specific webclient stuff
}
using (WebClient client= new WebClient())
{
Textbox1.text = "hey";
//specific webclient stuff
MessageBox.show("Random");
}
这两个在性能上有区别吗?
using webclient
里面没有webclient
相关的东西可以吗?
在小规模上它并没有太大的区别,但为了最佳实践,我会坚持只在需要时实例化 webclient 并在完成后立即处理它,如果你遵循最佳实践即使对于很小的项目,它也使得长期 运行 遵循大型项目的最佳实践变得更加容易。
对于 WebClient
来说确实没有太大区别。诀窍是通常尝试尽快使用处置资源。
我倾向于做这样的事情:
public static class WebClientEx
{
public static T Using<T>(this Func<WebClient, T> factory)
{
using (var wc = new WebClient()
{
return factory(wc);
}
}
}
然后我可以这样调用代码:
Textbox1.text = "hey";
string text = WebClientEx.Using(wc => wc.DownloadString(@"url"));
MessageBox.show(text);
甚至:
Func<WebClient, string> fetch = wc => wc.DownloadString(@"url");
Textbox1.text = "hey";
string text = fetch.Using();
MessageBox.show(text);
这最大限度地减少了创建 WebClient
的时间,并使代码保持相当整洁。
using (WebClient client= new WebClient())
{
//specific webclient stuff
}
using (WebClient client= new WebClient())
{
Textbox1.text = "hey";
//specific webclient stuff
MessageBox.show("Random");
}
这两个在性能上有区别吗?
using webclient
里面没有webclient
相关的东西可以吗?
在小规模上它并没有太大的区别,但为了最佳实践,我会坚持只在需要时实例化 webclient 并在完成后立即处理它,如果你遵循最佳实践即使对于很小的项目,它也使得长期 运行 遵循大型项目的最佳实践变得更加容易。
对于 WebClient
来说确实没有太大区别。诀窍是通常尝试尽快使用处置资源。
我倾向于做这样的事情:
public static class WebClientEx
{
public static T Using<T>(this Func<WebClient, T> factory)
{
using (var wc = new WebClient()
{
return factory(wc);
}
}
}
然后我可以这样调用代码:
Textbox1.text = "hey";
string text = WebClientEx.Using(wc => wc.DownloadString(@"url"));
MessageBox.show(text);
甚至:
Func<WebClient, string> fetch = wc => wc.DownloadString(@"url");
Textbox1.text = "hey";
string text = fetch.Using();
MessageBox.show(text);
这最大限度地减少了创建 WebClient
的时间,并使代码保持相当整洁。