这主要是为了好奇,因为有我能想到的实现几乎所有用例的更好的方式为这个结构(在C#和其他语言我经常使用,至少),但我最近看到在这里一个范围的互斥这是一个很酷的概念.
我的问题是,using语句是否维护一个引用(即:阻止GC运行)到它所作用的对象?
例如,如果我这样做:
using (new ScopedMutex())
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
ScopedMutex对象是否会在使用块结束时保持其存在,或者GC可以在块中运行并处理它吗?
可以在使用块内捕获异常,如果是,那么语法是什么?
所以,如下所示:
using (var creatingThing = new MyCreatingThing())
{
creatingThing.CreateSomething();
catch()
{
creatingThing.Rollback();
}
}
Run Code Online (Sandbox Code Playgroud)
可以这样做吗?或者我是否需要手动编写此代码(即不使用)?
什么是更好的,使用指令,或完成对象时的dispose指令?
using(FileStream fileStream = new FileStream(
"logs/myapp.log",
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using(StreamReader streamReader = new StreamReader(fileStream))
{
this.textBoxLogs.Text = streamReader.ReadToEnd();
}
}
Run Code Online (Sandbox Code Playgroud)
另一方面,当我正在处理System.Net.Mail时,我被告知我需要对象的Dispose()来释放任何杂散锁.
有没有一致的指导?如何判断在给定对象的特定情况下哪些更合适?
我遇到的有趣问题是完全有道理的.我有一个像这样的通用方法:
public TResult Run<TResult>(Func<SqlDataReader, TResult> resultDelegate)
{
TResult result;
using (SqlDataReader reader = command.ExecuteReader()) // command is SqlCommand with attached SqlConnection
{
result = resultsDelegate(reader);
}
// Some other unrelated code (but that's why result has a variable)
return result;
}
Run Code Online (Sandbox Code Playgroud)
在一种情况下,resultDelegate返回类型(TResult)是IEnumerable<object>.问题是Run由于延迟执行,函数立即返回,处理SqlDataReader.稍后在代码中,当我尝试读取结果时(代表所做的reader.Read(),我得到了一个InvalidOperationException: Invalid attempt to call Read when reader is closed.
我很难找到解决这个问题的最佳方法.我知道我可以返回一个具体的清单,但如果可能的话我想避免这样做.我也可以在委托中移动using语句,但是再一次,如果我可以避免为每个委托做这个,那就太好了.有任何想法吗?
我有名称空间:
MyProject.Core.Db
MyProject.Core.Model
Run Code Online (Sandbox Code Playgroud)
我有课:
MyProject.Core.Db.User
MyProject.Core.Model.User
Run Code Online (Sandbox Code Playgroud)
是否可能像这样:
using MyProject.Core;
namespace MyProject.BLL
{
public class Logic
{
public static void DoSomething()
{
var userEntity = new Db.User();
var userModel = new Model.User();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我只想避免在类名(UserModel,UserEntity)中使用后缀。
是否可以在C#中以某种方式进行?
我在Visual Basic中使用using语句很困难.有谁知道应该怎么写?:
Using (Dim doc As WordprocessingDocument = WordprocessingDocument.Open(filename, True))
//blah blah
End Using
Run Code Online (Sandbox Code Playgroud)
代码在没有使用的情况下工作正常,它显然是语法错误."Dim"突出显示,并且显然表达了一种表达.很抱歉,如果这有点基础,但vb使用语句的信息不清楚,它显然不适用于c#样式.
我正在处理我需要访问数据库的应用程序.使用using语句很好,因为"using" statement is to ensure that the object is always disposed correctly, and it doesn't require explicit code to ensure that this happens.我有点困惑在哪里使用"使用",哪里不使用.
public int route(Route r)
{
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using(SqlCommand com = new SqlCommand("",con))
{
using (SqlDataReader sdr = com.ExecuteReader())
{
}
}
}
}
catch (Exception e)
{
}
}
Run Code Online (Sandbox Code Playgroud) 我从像许多来源理解这个和这个,该Dispose的方法IDisposable如果有异常被抛出总是被称为Using块.那么我有这个代码:
static class MainEntryPoint
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += HandleUnhandledException;
using (var x = new Disposable())
{
throw new Exception("asdfsdf");
}
}
private static void HandleUnhandledException(Object sender, System.UnhandledExceptionEventArgs e)
{
Environment.Exit(0);
}
}
class Disposable : IDisposable
{
public void Dispose()
{
System.Diagnostics.Debug.Print("I am disposed");
}
}
Run Code Online (Sandbox Code Playgroud)
当抛出未处理的异常时,它退出应用程序.Dispose永远不会调用该方法.为什么?
假定基类Foo实现IDisposable。类FooA并FooB继承Foo类。一个简单的工厂方法,FooFactory.Create()根据客户端的需要返回FooA或FooB对象。
在下面的客户端代码(FooTest模块)中,尝试在“使用”语句中使用工厂方法会导致以下编译错误:
“使用”资源变量必须具有显式初始化。
我非常感谢有关通过Using语句支持实例化FooA或FooB(由客户端指定)的实现的任何建议(最佳实践)。不需要工厂-这只是我尝试的方法。理想情况下,我希望FooA和FooB是具有公共基类或接口的独立类。
在此先感谢您提供的任何帮助。
Public Module FooTest
Public Sub Test()
'the following compiles:
Dim f As Foo = FooFactory.Create("A")
f.DoWork()
f.Dispose()
'the following causes a compile error:
''Using' resource variable must have an explicit initialization.
Using f As FooFactory.Create("A")
f.DoWork()
End Using
End Sub
End Module
Public Module FooFactory
Public Function Create(ByVal AorB As String) As Foo
If AorB = "A" Then
Return New FooA
Else
Return New FooB
End If
End Function …Run Code Online (Sandbox Code Playgroud) 以下代码在执行时不会产生错误:
using ((IDisposable)null) {
Console.WriteLine("A");
}
Console.WriteLine("B");
Run Code Online (Sandbox Code Playgroud)
是'允许' 的空值using?如果是这样,它在哪里记录?
我见过的大多数C#代码都会创建一个"dummy/NOP"IDisposable对象 - 是否特别需要非null的Disposable对象?有没有?
如果/因为空是允许的,它允许将一个空后卫内 using语句来之前或周围的反对.
使用C#Reference没有提到空值.
using-statement ×10
c# ×7
.net ×4
idisposable ×2
using ×2
vb.net ×2
asp.net ×1
com ×1
delegates ×1
dispose ×1
exception ×1
factory ×1
namespaces ×1
null ×1
syntax-error ×1
try-catch ×1