I want to create my custom statements for the c# compiler to generate a try finally block. Just like the lock statement.
Forexample
private readonly ReaderWriterLockSlim _lockObject
private void MyMethod()
{
MyWriteLock(lockObject)
{
}
}
private void MyMethod2()
{
MyReadLock(lockObject)
{
}
}
Compiler should generate following code for me
private void MyMethod()
{
try
{
lockObject.EnterWriteLock();
.. statetments for the method
}
finally
{
_lockObject.ExitWriteLock();
}
}
private void MyMethod2()
{
try
{
lockObject.EnterReadLock();
.. statetments for the method
}
finally
{
_lockObject.ExitReadLock();
}
}
You can't create your own statements in C#. The closest you can come for try/finally is a using
statement:
using (lockObject.AcquireReadToken())
{
}
where AcquireReadToken()
would acquire a read lock, and return an IDisposable
which releases the lock when it's disposed.
You should give a try to ILWeaving . I haven't tried that, but a lot of 'magic' can be done using ILWeaving. I use NotifyPropertyWeaver which uses ILWeaving to inject code.
Refer this question
You could do this with ILWeaving using one of the following
However I think in this case making use of a 'using' statement as suggested by @JonSkeet would be the much simpler solution.
That is, of course, unless you are interested in learning about IL Manipulation. In which case go for it :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.