// </Snippet4> public static void Main() { int result; int param; // <Snippet6> // Creates an instance of a context-bound type SampleSynchronized. SampleSynchronized sampSyncObj = new SampleSynchronized(); // Checks whether the object is a proxy, since it is context-bound. if (RemotingServices.IsTransparentProxy(sampSyncObj)) Console.WriteLine("sampSyncObj is a proxy."); else Console.WriteLine("sampSyncObj is NOT a proxy."); // </Snippet6> // <Snippet7> param = 10; Console.WriteLine(""); Console.WriteLine("Making a synchronous call on the context-bound object:"); result = sampSyncObj.Square(param); Console.Write("The result of calling sampSyncObj.Square with "); Console.WriteLine("{0} is {1}.", param, result); Console.WriteLine(""); // </Snippet7> // <Snippet8> SampSyncSqrDelegate sampleDelegate = new SampSyncSqrDelegate(sampSyncObj.Square); param = 8; Console.WriteLine("Making a single asynchronous call on the context-bound object:"); IAsyncResult ar1 = sampleDelegate.BeginInvoke( param, new AsyncCallback(AsyncResultSample.MyCallback), param); Console.WriteLine("Waiting for the asynchronous call to complete..."); WaitHandle wh = ar1.AsyncWaitHandle; wh.WaitOne(); wh.Close(); Console.WriteLine(""); Console.WriteLine("Waiting for the AsyncCallback to complete..."); // Note that normally, a callback and a wait handle would not // both be used on the same asynchronous call. Callbacks are // useful in cases where the original thread does not need to // be synchronized with the result of the call, and in that // scenario they provide a place to call EndInvoke. Sleep is // used here because the callback is on a ThreadPool thread. // ThreadPool threads are background threads, and will not keep // a process running when the main thread ends. Thread.Sleep(1000); // </Snippet8> }
static void Main(string[] args) { SampleSynchronized sampleSynchronized = new SampleSynchronized(); List <Thread> threads = new List <Thread>(); for (int i = 0; i < 10; i++) { var i1 = i; Thread thread = new Thread(o => { sampleSynchronized.Square(i1); }); threads.Add(thread); } foreach (Thread thread in threads) { thread.Start(); } Console.WriteLine("Main app is finished."); Console.ReadKey(); }