如何在我的函数中返回一个一次性对象以确保它在using块内正常工作?在我的函数中,我想对一次性对象进行操作并考虑错误,这使问题变得复杂。
到目前为止,我有类似于以下代码的内容:
DBHandle GetDB()
{
/* // I can't do this, because the using block would dispose of my object within this function
using( var db = DatabaseObj.GetHandle() )
{
db.Open();
return db;
}
*/
var db = DatabaseObj.GetHandle();
try
{
db.Open();
return db;
}
catch (Exception ex)
{
db.Dispose();
throw ex;
}
}
// In other code:
using( var obj = GetDB() ){ /* ... */ }
Run Code Online (Sandbox Code Playgroud)
我想知道我的使用using是否正确.在using统计中,我决定是否应该在游戏中使用图像.
Image imageOfEnemy;
using(imageOfEnemy=Bitmap.FromFile(path))
{
// some stuff with the imageOfEnemy variable
}
Run Code Online (Sandbox Code Playgroud)
根据我的理解,我现在不需要打电话Dispose.
using声明刚刚被引入,C# 8.0但它们的行为与using块不同,或者我认为。
以下嵌套using块工作正常:
using (var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream(serviceKey))
using (var file = new FileStream(path, FileMode.Create, FileAccess.Write))
{
resource?.CopyTo(file);
}
Run Code Online (Sandbox Code Playgroud)
但是当我转换using为如下声明时,我得到一个IOException表示该文件正在被另一个进程使用的信息:
using var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream(serviceKey);
using var file = new FileStream(path, FileMode.Create, FileAccess.Write);
resource?.CopyTo(file);
Run Code Online (Sandbox Code Playgroud)
我想了解有什么不同以及如何\何时使用新using声明?
我试图从多个数据库表中删除记录.对于错误处理,我正在使用下面看到的try/catch块.
try
{
using (SqlCeConnection oConn = new SqlCeConnection(ConnectionString))
{
oConn.Open();
using (SqlCeTransaction transaction = oConn.BeginTransaction())
{
//delete from multiple tables using ADO.NET
transaction.Commit();
}
}
}
catch
{
//error handling
}
Run Code Online (Sandbox Code Playgroud)
问题是当引发异常时,事务不会回滚.在阅读多个论坛时,我的结论是"使用"语句应该处理事务和连接.处置时,应回滚未提交的事务.
有人能告诉我我做错了什么.
据我所知,使用像try/catch/finally这样的工作,所以我希望如果在using语句中发生异常它会被捕获(这有点奇怪,因为这也意味着异常被默默地吃掉了).using语句应该捕获异常并调用Dispose方法,但是,没有发生.我已经设计了一个简单的测试来证明这个问题.
这是我强制在using语句中发生异常的地方:
using (TcpClient client = new TcpClient())
{
// Why does this throw when the using statement is supposed to be a try/catch/finally?
client.Connect(null);
}
Run Code Online (Sandbox Code Playgroud)
抛出异常client.Connect()(意味着它没有被using语句捕获或者被重新抛出):
System.ArgumentNullException: Value cannot be null.
Parameter name: remoteEP
at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
at DotNETSandbox.Program.Main(String[] args) in C:\path\to\Sandbox\Program.cs:line 42
Run Code Online (Sandbox Code Playgroud)
根据微软关于该主题的文章,如果Dispose方法抛出,则可能会抛出using语句.
但是,当我遵循使用模式时,显然Dispose方法不会抛出:
TcpClient c2 = new TcpClient();
try
{
c2.Connect(null);
}
catch (Exception e)
{
// We caught the null ref exception
try
{
// Try to dispose: …Run Code Online (Sandbox Code Playgroud) 我有这个代码:
using (var requestStream = request.GetRequestStream())
{
byte[] data = Encoding.UTF8.GetBytes(xmlData);
requestStream.Write(data, 0, data.Length);
}
Run Code Online (Sandbox Code Playgroud)
如果由于远程服务器关闭而导致我的请求失败,我该如何捕获错误?
我应该将使用块扩展到try-catch-finally,还是使用"使用"块时有更优雅的方法?
(我需要以这种方式只捕获服务器正在下降的类型错误 - 我需要向客户端显示这些错误,因为他们的服务器连接不充分,而不是因为我们的软件中的错误或其他东西).
我遇到了一些麻烦.我在一个使用块中有一个SqlCommand.通常这很好.但是,这次代码退出使用块,但命令没有被释放.这让我很难过.
using (SqlCommand transferCommand = new SqlCommand(strHeaderStoredProcedure, connection))
{
transferCommand.CommandType = System.Data.CommandType.StoredProcedure;
transferCommand.Parameters.Add("@InvtTransferID", SqlDbType.UniqueIdentifier).Value = InvtTransferID;
SqlDataReader transferReader = transferCommand.ExecuteReader();
while (transferReader.Read())
{
//do my stuff, this all works fine
}
}
using (SqlCommand transferCommand = new SqlCommand(strDetailsStoredProcedure, connection))
{
transferCommand.CommandType = System.Data.CommandType.StoredProcedure;
transferCommand.Parameters.Add("@InvtTransferID", SqlDbType.UniqueIdentifier).Value = InvtTransferID;
SqlDataReader transferReader = transferCommand.ExecuteReader(); <-- Error happens here.
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试重用我的连接来运行一堆存储过程.这是最奇怪的事情.我在另一个几乎相同的表单上有一些代码,它运行正常,处理命令并允许我创建另一个.我有什么想法我做错了吗?(我正试图让这段代码在帖子中看起来不错,但它似乎超出了我的微薄力量...对于凌乱的代码感到抱歉.)
错误是:已经有一个与此命令关联的打开DataReader,必须先关闭它.
我有一个Xmlreader,我想加载到'using'中的XMLDocument中:但是,问题是XMLDocument在完成后被处理掉(在xml.Load(reader)之后).我试过在'using'中包含一个int变量,它也会被处理掉.但是,在我创建'result'字符串的第一个'using'中,它在离开语句后不会被释放.为什么会这样?
HttpWebRequest req = WebRequest.Create(URL_GET.ToString()) as HttpWebRequest;
string result = null;
using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}
using (XmlReader reader = XmlReader.Create(new StringReader(result)))
{
reader.ReadToFollowing("ops:output");
XmlDocument xml = new XmlDocument();
xml.Load(reader);
}
Run Code Online (Sandbox Code Playgroud) 我写了两个代码:
代码块1:
Stream dataStream;
using (var response = (HttpWebResponse)req.GetResponse())
{
dataStream = response.GetResponseStream();
}
//Open the stream using a StreamReader for easy access
using (var reader = new StreamReader(dataStream))
{
data = reader.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)
代码块2:
Stream dataStream;
using (var response = (HttpWebResponse)req.GetResponse())
{
dataStream = response.GetResponseStream();
//Open the stream using a StreamReader for easy access
using (var reader = new StreamReader(dataStream))
{
data = reader.ReadToEnd();
}
}
Run Code Online (Sandbox Code Playgroud)
代码块1抛出错误:stream is not reachable.
虽然在进步中我认为两个代码将工作相同.
我在代码块2中添加了使用块到整个语句,它正在工作.
但我很困惑,为什么它会在代码块1中抛出错误
假设我有以下方法:
public string GetSchedules(string request)
{
using (var soapClient = new ServiceReference1.CustomDataTimetableToolKitServicesSoapClient(EndpointConfiguratioName, Endpoint))
{
return soapClient.GetSchedules(AuthenticationInfo, request);
}
}
public string GetCountryList(string request)
{
using (var soapClient = new ServiceReference1.CustomDataTimetableToolKitServicesSoapClient(EndpointConfiguratioName, Endpoint))
{
return soapClient.GetCountryList(AuthenticationInfo, request);
}
}
public string GetCarriers(string request)
{
using (var soapClient = new ServiceReference1.CustomDataTimetableToolKitServicesSoapClient(EndpointConfiguratioName, Endpoint))
{
return soapClient.GetCarriers(AuthenticationInfo, request);
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,唯一不同的是调用方法的名称.我怎么能重构这些方法只应用"using"语句一次并避免代码重复?
c# ×10
using-statement ×10
.net ×2
ado.net ×2
dispose ×2
try-catch ×2
exception ×1
httprequest ×1
idisposable ×1
refactoring ×1
sqlcommand ×1
transactions ×1
wcf ×1