gpt4 book ai didi

c# - 这对于使用 IDisposable 处理对象是否正确

转载 作者:太空宇宙 更新时间:2023-11-03 17:09:29 26 4
gpt4 key购买 nike

我有一个实现 IDisposable 接口(interface)的类。我正在使用网络客户端使用 AsyncDownloadString 下载一些数据。

我想知道我是否在 Web 客户端的构造函数和 using 语句中正确声明了我的事件处理程序?这是在 Dispose 方法中删除事件处理程序的正确方法吗?

否决这是使用 IDisposable 接口(interface)的正确方法吗?

public class Balance : IDisposable
{
//Constructor
WebClient wc;
public Balance()
{
using (wc = new WebClient())
{
//Create event handler for the progress changed and download completed events
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
}
}

~Balance()
{
this.Dispose(false);
}

//Get the current balance for the user that is logged in.
//If the balance returned from the server is NULL display error to the user.
//Null could occur if the DB has been stopped or the server is down.
public void GetBalance(string sipUsername)
{
//Remove the underscore ( _ ) from the username, as this is not needed to get the balance.
sipUsername = sipUsername.Remove(0, 1);

string strURL =
string.Format("https://www.xxxxxxx.com",
sipUsername);

//Download only when the webclient is not busy.
if (!wc.IsBusy)
{
// Download the current balance.
wc.DownloadStringAsync(new Uri(strURL));
}
else
{
Console.Write("Busy please try again");
}
}

//return and display the balance after the download has fully completed
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//Pass the result to the event handler
}

//Dispose of the balance object
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

//Remove the event handlers
private bool isDisposed = false;
private void Dispose(bool disposing)
{
if (!this.isDisposed)
{
if (disposing)
{
wc.DownloadProgressChanged -= new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadStringCompleted -= new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);

wc.Dispose();
}
isDisposed = true;
}
}
}

最佳答案

有两种使用 IDisposable 对象的正确方法:

  1. 将其放在using block 中
  2. 将它包装在一个同样正确实现 IDisposable 的类中,并在处理这个新类时将其处理掉。您现在希望新类的所有实例都是使用 using block 创建的。

请注意,我说的是“或”,而不是“和”。做一个或另一个,但不能同时做。

在这里,当您在构造函数中使用 using block 创建 WebClient 实例时,您会在有机会在其他任何地方使用它之前将其处置掉。在这种情况下,您应该只执行选项二。

关于c# - 这对于使用 IDisposable 处理对象是否正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/876062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com