locked
trick: run (piece of) code atomically in .cshtml files RRS feed

  • Question

  • User1129400750 posted

    i didn't find anything, so here it is the trick from my exeperiments ... i won't write too much as is really really simple and it keeps the code simple and readable without needing of heavy rewriting

    put

    @functions {
    
        static object _locker = new Object();
    
    }

    wherever you want in your file, _locker will be shared across all page calls ... now you can run your code atomically

    lock (_locker) {
    
       ... update db ...
    
    
       ... update global stuff ...
    
    
       .. update db ...
    
    
    }

    that's all...please share if you have any idea to improve, thanks

    Saturday, January 4, 2014 5:42 PM

All replies

  • User1129400750 posted

    little improvement...add in App_Code, Locker.cshtml

    @using System.Collections
    @using System.Collections.Concurrent
    
    
    @functions {
    
    	private static ConcurrentDictionary<string, object> _locker = new ConcurrentDictionary<string, object>();
    
    	
    	public static object GetLock (string name) {

    lock (_locker) { return( _locker.GetOrAdd(name, key => new Object()) );

    } } }

    so we have no need to add the _locker object in every page e we can write something like that

    lock (Locker.GetLock(VirtualPath)) {
    
       ... update db ...
    
    
       ... update global stuff ...
    
    
       .. update db ...
    
    
    }

    Sunday, January 5, 2014 8:08 AM