我怎样才能在C#中创建一个锁定方法
即。锁的模式是
lock(inputParam)
{
// code here
}
我想用类似的使用模式创建一个类似的方法,在括号内的代码之前和之后内部执行一些代码,
SomeFunc(InputParam)
{
// Do some stuff
}
锁定是C#中的一个特例,还是我们能够用某种lambda / action暗魔法获得类似的结果?
答案 0 :(得分:3)
没有黑魔法。你想要的是try/finally
:
DoSomething();
try
{
// lots of stuff here
}
finally
{
// do other stuff
}
我想你可以编写一个为你做的方法:
void DoTryFinally(Action start, Action stuff, Action final)
{
start();
try
{
stuff();
}
finally
{
final();
}
}
并称之为:
DoTryFinally(
() => { /* start stuff here */ },
() => { /* stuff here */ },
() => { /* final stuff here */ });
我建议第一种方式:try/finally
是C#中常见的习语。
顺便说一句,您发布的代码:
lock (someObject)
{
// do stuff
}
实际上只是简单的简写:
Monitor.Enter(someObject);
try
{
// do stuff
}
finally
{
Monitor.Exit(someObject);
}
编译器在编译lock
语句时生成它。
编译器内置了无法使用任意功能的工具。 Dispose pattern接近,但这不是一般解决方案。
答案 1 :(得分:1)
lock
只是有点特别:它在C#规范中提到,但相当于你可以编写的代码(见the spec的§8.12)。你可以做一些模糊相似的事情:
void Main()
{
SomeFunc(2, () => {
//do stuff
});
}
public void SomeFunc(int inputParam, Action body)
{
//do before stuff
body();
// do after stuff
}
然而,这种模式听起来很不寻常。在假设这是一个很好的方法之前,我会看看是否有更好的方法来做我想做的事情。