在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相关的内容?

在小范围内,它并没有真正产生太大的差异,但对于最佳实践,我会坚持只在需要时实例化web客户端,并在完成后立即处理它,如果您遵循即使是小项目的最佳实践,那么从长远来看,遵循大型项目的最佳实践会更容易。

这对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的时间,并使代码保持相当整洁。

最新更新