Implementing RegEx Timeout in .NET 4

后端 未结 4 1711
情歌与酒
情歌与酒 2020-12-09 00:33

Platform: Silverlight 4, .NET 4

With the .NET 4.5 Developer preview the RegEx class has been enhanced to allow setting of a Timeout value which would prevent the Reg

4条回答
  •  天命终不由人
    2020-12-09 00:44

    I re-implemented the above code changing it in a way that I belive is more reliable.

        /// 
        /// Executes function proc on a separate thread respecting the given timeout value.
        /// 
        /// 
        /// The function to execute.
        /// The timeout duration.
        /// 
        public static R ExecuteWithTimeout(Func proc, TimeSpan timeout) {
            var r = default(R); // init default return value
            Exception ex = null; // records inter-thread exception
    
            // define a thread to wrap 'proc'
            var t = new Thread(() => {
                try {
                    r = proc();
                    }
                catch (Exception e) {
                    // this can get set to ThreadAbortException
                    ex = e;
    
                    Debug.WriteLine("Exception hit");
    
                    }
                });
    
            t.Start(); // start running 'proc' thread wrapper
            // from docs: "The Start method does not return until the new thread has started running."
    
            if (t.Join(timeout) == false) {
                t.Abort(); // die evil thread!
                // Abort raises the ThreadAbortException
                int i = 0;
                while ((t.Join(1) == false) && (i < 20)) { // 20 ms wait possible here
                    i++;
                    }
                if (i >= 20) {
                    // we didn't abort, might want to log this or take some other action
                    // this can happen if you are doing something indefinitely hinky in a
                    // finally block (cause the finally be will executed before the Abort 
                    // completes.
                    Debug.WriteLine("Abort didn't work as expected");
                    }
                }
    
            if (ex != null) {
                throw ex; // oops
                }
            return r; // ah!
            } 
    

提交回复
热议问题