我需要强制使用"使用"来处理类的新实例.
public class MyClass : IDisposable
{
...
}
using(MyClass obj = new MyClass()) // Force to use "using"
{
}
Run Code Online (Sandbox Code Playgroud) 是否可以通过finally
抛出异常来确定代码当前是否在处理程序的上下文中执行?我非常喜欢使用IDisposable
模式来实现入口/出口作用域功能,但是这种模式的一个问题是,如果在主体中发生异常,您可能不一定希望发生作用域结束行为using
.我会找这样的东西:
public static class MyClass
{
public static void MyMethod()
{
using (var scope = MyScopedBehavior.Begin())
{
//Do stuff with scope here
}
}
}
public sealed class MyScopedBehavior : IDisposable
{
private MyScopedBehavior()
{
//Start of scope behavior
}
public void Dispose()
{
//I only want to execute the following if we're not unwinding
//through finally due to an exception:
//...End of scope behavior
}
public static MyScopedBehavior Begin()
{
return new MyScopedBehavior(); …
Run Code Online (Sandbox Code Playgroud) 我是C#的新手,如果这是一个明显的问题,请道歉.
在MSDN Dispose示例中,它们定义的Dispose方法是非虚拟的.这是为什么?这对我来说似乎很奇怪 - 我希望IDisposable的子类具有自己的非托管资源,它只会覆盖Dispose并在自己的方法底部调用base.Dispose().
谢谢!
所以,我有一个从WCF服务公开的方法:
public GetAllCommentsResponse GetAllComments(GetAllCommentsRequest request)
{
var response = new GetAllCommentsResponse();
using(_unitOfWork)
try
{
Guard.ArgNotNull(request, "request");
var results = _unitOfWork.CommentRepository.Get(d => d.Id > 0).ToArray();
//... Do rest of stuff here
}
catch (Exception ex)
{
response.Success = false;
response.FailureInformation = ex.Message;
Logger.LogError("GetAllComments Method Failed", ex);
}
return response;
}
Run Code Online (Sandbox Code Playgroud)
我有一个全局DataUnitOfWork对象(实现IDisposable),当服务调用进来时,Ninject通过构造函数参数实例化.当调试时,如果我使用
using(_unitOfWork)
Run Code Online (Sandbox Code Playgroud)
超出范围后,_unitOfWork对象立即被释放,然后被Ninject再次调用(尽管它被标记为已丢弃,因此没有任何反应.)如果没有using语句,Ninject将处理处理.
长话短说,这是否有一般的经验法则?在我阅读的所有内容似乎表明永远不会使用它,或者在某些折衷的情况下使用它之后,我一直害怕整个IDisposable的东西,但它总是让我感到困惑.
任何输入都表示赞赏.
哦,当我在这里打字时,为什么在处理时确实有GC.SuppressFinalize()的调用?Dispose和Finalize有何不同?
我正在迭代一个ManageObjectCollection.(这是WMI接口的一部分).
但重要的是,以下代码行.:
foreach (ManagementObject result in results)
{
//code here
}
Run Code Online (Sandbox Code Playgroud)
关键是ManageObject也实现了IDisposable,所以我想把"result"变量放在using块中.关于如何做到这一点的任何想法,而不是太奇怪或复杂?
我有以下代码,但它很尴尬.我怎么能更好地构建它?我是否必须使我的消费类实现IDisposable并有条件地构建网络访问类并在我完成后处理它?
protected void ValidateExportDirectoryExists()
{
if (useNetworkAccess)
{
using (new Core.NetworkAccess(username, password, domain))
{
CheckExportDirectoryExists();
}
}
else
{
CheckExportDirectoryExists();
}
}
Run Code Online (Sandbox Code Playgroud) 想象一下IDisposable
接口的实现 ,它有一些公共方法.
如果在多个线程之间共享该类型的实例并且其中一个线程可以处置它,那么确保其他线程在处置后不尝试使用该实例的最佳方法是什么?在大多数情况下,在处理对象之后,其方法必须知道它并抛出ObjectDisposedException
或者InvalidOperationException
或者至少通知调用代码做错事.我是否需要为每种方法进行同步- 尤其是在检查它是否被丢弃时?IDisposable
使用其他公共方法的所有实现都需要是线程安全的吗?
这是一个例子:
public class DummyDisposable : IDisposable
{
private bool _disposed = false;
public void Dispose()
{
_disposed = true;
// actual dispose logic
}
public void DoSomething()
{
// maybe synchronize around the if block?
if (_disposed)
{
throw new ObjectDisposedException("The current instance has been disposed!");
}
// DoSomething logic
}
public void DoSomethingElse()
{
// Same sync logic as in DoSomething() again?
}
}
Run Code Online (Sandbox Code Playgroud) 在该IDisposable.Dispose
方法中有一种方法可以确定是否抛出异常?
using (MyWrapper wrapper = new MyWrapper())
{
throw new Exception("Bad error.");
}
Run Code Online (Sandbox Code Playgroud)
如果在using
语句中抛出异常,我想在处理IDisposable
对象时知道它.
请考虑以下代码:
namespace DisposeTest
{
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Calling Test");
Test();
Console.WriteLine("Call to Test done");
}
static void Test()
{
DisposeImplementation di = new DisposeImplementation();
}
}
internal class DisposeImplementation : IDisposable
{
~DisposeImplementation()
{
Console.WriteLine("~ in DisposeImplementation instance called");
}
public void Dispose()
{
Console.WriteLine("Dispose in DisposeImplementation instance called");
}
}
}
Run Code Online (Sandbox Code Playgroud)
即使我在Test();
调用之后放置了一个等待循环,Dispose也永远不会被调用.所以这很糟糕.我想编写一个简单易用的类,以确保清理所有可能的资源.我不想把这个责任交给我班级的用户.
可能的解决方案:使用using
或调用自己处理(基本相同).我可以强制用户使用吗?或者我可以强制调用处理吗?
呼叫GC.Collect();
后Test();
也不起作用.
把di
以null
不调用任何处置.解构器可以工作,因此对象在退出时会被解构Test()
好的,现在很清楚!
谢谢大家的答案!我会在评论中添加警告!
我有以下代码:
public void Dispose()
{
if (_instance != null)
{
_instance = null;
// Call GC.SupressFinalize to take this object off the finalization
// queue and prevent finalization code for this object from
// executing a second time.
GC.SuppressFinalize(this);
}
}
Run Code Online (Sandbox Code Playgroud)
虽然有一条评论解释了与GC相关的电话的目的,但我仍然不明白为什么会这样.
一旦所有实例都停止存在,就不会将对象注定为垃圾收集,例如,当在using
块中使用时?
什么是用例场景,它将发挥重要作用?