zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#-Monitor-多线程 不阻塞线程 无法执行时 放弃

c#多线程线程执行 无法 阻塞 放弃 monitor
2023-09-11 14:21:57 时间
public void TestMethod1() {
            object _lock = new object();

            Action a1 = () => {
                if ( Monitor.TryEnter( _lock ) ) {
                    try {

                        for ( int i = 0; i < 10; i++ ) {
                            Debug.Print( "a1\t" + i );
                        }
                    } catch ( Exception ex ) {
                        Debug.Print( " a1 occur error : " + ex.Message );
                    } finally {
                        Monitor.Exit( _lock );
                    }
                }
            };
            Action a2 = () => {
                if ( Monitor.TryEnter( _lock ) ) {
                    try {
                        for ( int i = 0; i < 10; i++ ) {
                            Debug.Print( "a2\t" + i );
                        }
                    } catch ( Exception ex ) {
                        Debug.Print( "a2 occur error : " + ex.Message );
                    } finally {
                        Monitor.Exit( _lock );
                    }
                }
            };

            Parallel.Invoke( a1, a2 );


        }