线程同步与异步
代码
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Reflection;
6 using System.Threading;
7
8 namespace AppDomain_test
9 {
10 class Program
11 {
12 #region Test1
13
14 //static void Main(string[] args)
15 //{
16 // #region AppDomain_test1
17 // //AppDomain curAppDomain = AppDomain.CurrentDomain;
18 // //foreach (Assembly assembly in curAppDomain.GetAssemblies())
19 // //{
20 // // Console.WriteLine(assembly.FullName);
21 // //}
22 // #endregion
23
24 // #region domain1
25 // //Console.WriteLine("Thread :{0} Hi from the domain:{1}", Thread.CurrentThread.Name, AppDomain.CurrentDomain.FriendlyName);
26 // #endregion
27
28 // #region CallingConventions
29
30 // //Thread.CurrentThread.Name = "MyThread";
31
32 // //AppDomainSetup info = new AppDomainSetup();
33 // //info.ApplicationBase = "file://" + Environment.CurrentDirectory;
34 // //AppDomain newDomain = AppDomain.CreateDomain("NewDomain", null, info);
35 // //Console.WriteLine("Thread{0} Calling ExecuteAssembly() from appdomain{1}", Thread.CurrentThread.Name, AppDomain.CurrentDomain.FriendlyName);
36 // //newDomain.ExecuteAssembly("AssemblyToLoad.exe");
37 // //AppDomain.Unload(newDomain);
38 // #endregion
39
40 // #region 在其他AppDomain 的上下文中运行代码
41 // //Thread.CurrentThread.Name = "MyThread";
42 // //AppDomain newDomain = AppDomain.CreateDomain("NewDomain");
43 // //CrossAppDomainDelegate deleg = new CrossAppDomainDelegate(Fct);
44 // //newDomain.DoCallBack(deleg);
45 // //AppDomain.Unload(newDomain);
46 // #endregion
47 //}
48
49 //#region 在其他AppDomain 的上下文中运行代码
50 ////public static void Fct()
51 ////{
52 //// Console.WriteLine("Thread:{0} execute Fct() inside the appdomain{1}",
53 //// Thread.CurrentThread.Name, AppDomain.CurrentDomain.FriendlyName);
54 ////}
55 //#endregion
56 #endregion
57
58 #region Test2
59 public static void Main()
60 {
61 AppDomain newDomain = AppDomain.CreateDomain("NewDomain");
62 CrossAppDomainDelegate deleg = new CrossAppDomainDelegate(Fct);
63
64 newDomain.DoCallBack(deleg);
65 int anInteger = (int)newDomain.GetData("AnInteger");
66 AppDomain.Unload(newDomain);
67 }
68
69 public static void Fct()
70 {
71 AppDomain.CurrentDomain.SetData("AnInteger ", 691);
72 }
73 #endregion
74
75
76
77
78 }
79
80
81 }
82
83
84
85 using System;
86 using System.Collections.Generic;
87 using System.Linq;
88 using System.Text;
89 using System.Diagnostics;
90 using System.Threading;
91 using System.IO;
92 using System.Runtime.Remoting.Contexts;
93
94 namespace Thead_Test
95 {
96 class Program
97 {
98 #region start notepad
99 //static void Main(string[] args)
100 //{
101 // Process process = Process.Start("notepad.exe", "hello.txt");
102
103 // Thread.Sleep(10000);
104 // process.Kill();
105 //}
106 #endregion
107
108 #region Join
109 //static long counter = 1;
110 //static void Main(string[] args)
111 //{
112 // Thread t1 = new Thread(f1);
113 // Thread t2 = new Thread(f2);
114 // t1.Start();
115 // t2.Start();
116 // t1.Join();
117 // t2.Join();
118
119 //}
120
121 //static void f1()
122 //{
123 // for (int i = 0; i < 5;i++ )
124 // {
125 // Interlocked.Increment(ref counter);
126 // Console.WriteLine("counter++ {0}", counter);
127 // Thread.Sleep(10);
128 // }
129 //}
130
131 //static void f2()
132 //{
133 // for (int i = 0; i < 5; i++)
134 // {
135 // Interlocked.Decrement(ref counter);
136 // Console.WriteLine("counter-- {0}", counter);
137 // Thread.Sleep(10);
138 // }
139 //}
140 #endregion
141
142 #region Monitor_Enter_Exit
143
144 //static long counter = 1;
145 //static void Main(string[] args)
146 //{
147 // Thread t1 = new Thread(f1);
148 // Thread t2 = new Thread(f2);
149 // t1.Start();
150 // t2.Start();
151 // t1.Join();
152 // t2.Join();
153
154 //}
155
156 //static void f1()
157 //{
158 // for (int i = 0; i < 5; i++)
159 // {
160 // Monitor.Enter(typeof(Program));
161 // try
162 // {
163 // counter *= counter;
164 // }
165 // finally
166 // {
167 // Monitor.Exit(typeof(Program));
168 // }
169
170 // Thread.Sleep(10);
171 // }
172 //}
173
174 //static void f2()
175 //{
176 // for (int i = 0; i < 5; i++)
177 // {
178 // Monitor.Enter(typeof(Program));
179 // try
180 // {
181 // counter *= 2;
182 // }
183 // finally
184 // {
185 // Monitor.Exit(typeof(Program));
186 // }
187 // Console.WriteLine("counter *2{0}", counter);
188 // Thread.Sleep(10);
189 // }
190 //}
191 #endregion
192
193 #region Lock
194
195 //static long counter = 1;
196 //static void Main(string[] args)
197 //{
198 // Thread t1 = new Thread(f1);
199 // Thread t2 = new Thread(f2);
200 // t1.Start();
201 // t2.Start();
202 // t1.Join();
203 // t2.Join();
204
205 //}
206
207 //static void f1()
208 //{
209 // for (int i = 0; i < 5; i++)
210 // {
211 // lock (typeof(Program)) ;
212 // {
213 // counter *= counter;
214 // }
215 // Console.WriteLine("counter ^2{0}", counter);
216 // Thread.Sleep(10);
217 // }
218 //}
219
220 //static void f2()
221 //{
222 // for (int i = 0; i < 5; i++)
223 // {
224 // lock(typeof(Program));
225 // {
226 // counter *= 2;
227 // }
228 // Console.WriteLine("counter *2{0}", counter);
229 // Thread.Sleep(10);
230 // }
231 //}
232 #endregion
233
234 #region SyncRoot
235 //class Foo
236 //{
237 // private static object staticSyncRoot = new object();
238 // private object instanceSyncRoot = new object();
239 // public static void StaticFct()
240 // {
241 // lock(staticSyncRoot)
242 // {
243
244 // }
245 // }
246
247 // public static void InstanceFct()
248 // {
249 // lock(instanceSyncRoot)
250 // {
251
252 // }
253 // }
254 //}
255 #endregion
256
257
258 #region 线程包装(线程安全类)
259 //class Foo
260 //{
261 // public virtual void Fct1(){}
262 // public virtual void Fct2(){}
263 // public virtual bool IsSynchronized{get{return false;}}
264
265 // public static Foo Synchronized(Foo foo)
266 // {
267 // if (!foo.IsSynchronized)
268 // {
269 // return new FooSynchronized(foo);
270 // }
271 // return foo;
272 // }
273
274 // private class FooSynchronized:Foo
275 // {
276 // private object syncRoot =new object();
277 // private Foo m_Foo;
278 // public FooSynchronized(Foo foo){m_Foo =foo;}
279 // public override bool IsSynchronized{get{return true;}}
280 // public override void Fct1(){lock(syncRoot){m_Foo.Fct1();}}
281 // public override void Fct2(){lock(syncRoot){m_Foo.Fct2();}}
282 // }
283 //}
284 #endregion
285
286 #region 测试TryEnter
287 //private static object staticSyncRoot = new object();
288 //static void Main()
289 //{
290 // Monitor.Enter(staticSyncRoot);
291 // Thread t1 = new Thread(f1);
292 // t1.Start();
293 // t1.Join();
294 //}
295
296 //static void f1()
297 //{
298 // if (!Monitor.TryEnter(staticSyncRoot))
299 // {
300 // return;
301 // }
302 // try
303 // {
304
305 // }
306 // finally
307 // {
308 // Monitor.Exit(staticSyncRoot);
309 // }
310 //}
311 #endregion
312
313 #region wait_pulse_lock
314 //static object ball = new object();
315 //public static void Main()
316 //{
317 // Thread threadPing = new Thread(ThreadPingProc);
318 // Thread threadPong = new Thread(ThreadPongProc);
319 // threadPing.Start();
320 // threadPong.Start();
321 // threadPing.Join();
322 // threadPong.Join();
323 //}
324
325 //static void ThreadPongProc()
326 //{
327 // Console.WriteLine("ThreadPong Hello");
328 // lock(ball)
329 // {
330 // for (int i = 0; i < 5;i++ )
331 // {
332 // Console.WriteLine("ThreadPong: Pong");
333 // Monitor.Pulse(ball);
334 // Monitor.Wait(ball);
335 // }
336 // }
337 // Console.WriteLine("ThreadPong:Bye!");
338 //}
339
340 //static void ThreadPingProc()
341 //{
342 // Console.WriteLine("ThreadPing Hello");
343 // lock (ball)
344 // {
345 // for (int i = 0; i < 5; i++)
346 // {
347 // Console.WriteLine("ThreadPing: Ping");
348 // Monitor.Pulse(ball);
349 // Monitor.Wait(ball);
350 // }
351 // }
352 // Console.WriteLine("ThreadPing:Bye!");
353 //}
354 #endregion
355
356 #region Mutex
357 //static void Main()
358 //{
359
360 // Mutex mutexFile = new Mutex(false, "MutexTest");
361 // for (int i =0;i<10;i++)
362 // {
363 // mutexFile.WaitOne();
364
365 // FileInfo fi = new FileInfo("tmp.txt");
366 // StreamWriter sw = fi.AppendText();
367 // sw.WriteLine("Hello{0}", i);
368 // sw.Flush();
369 // sw.Close();
370 // System.Console.WriteLine("Hello {0}", i);
371 // Thread.Sleep(1000);
372
373 // mutexFile.ReleaseMutex();
374 // }
375 // mutexFile.Close();
376 //}
377 #endregion
378
379 #region event EventHandler
380 //static EventHandler[] events;
381 //static void Main()
382 //{
383 // events = new EventWaitHandle[2];
384
385 // events[0] = new EventWaitHandle(false, EventResetMode.AutoReset);
386 // events[1] = new EventWaitHandle(false, EventResetMode.AutoReset);
387 // Thread t0 = new Thread(ThreadProc0);
388 // Thread t1 = new Thread(ThreadProc1);
389 // t0.Start();
390 // t1.Start();
391 // AutoResetEvent.WaitAll(events);
392 // Console.WriteLine("MainThread:Thread0 reached 2" + "and Thread1 reached 3.");
393 // t0.Join();
394 // t1.Join();
395 //}
396
397 //static void ThreadProc1()
398 //{
399 // for (int i = 0; i < 5;i++ )
400 // {
401 // Console.WriteLine("Thread0:{0}", i);
402 // if (i==2)
403 // {
404 // events[0].Set();
405 // }
406 // Thread.Sleep(100);
407 // }
408 //}
409
410 //static void ThreadProc2()
411 //{
412 // for (int i = 0; i < 5; i++)
413 // {
414 // Console.WriteLine("Thread0:{0}", i);
415 // if (i == 3)
416 // {
417 // events[1].Set();
418 // }
419 // Thread.Sleep(60);
420 // }
421 //}
422 #endregion
423
424 #region Thread.semmSemaphore
425
426 //static Semaphore semaphore;
427 //static void Main()
428 //{
429 // semaphore = new Semaphore(2, 5);
430 // for (int i = 0; i < 3;i++ )
431 // {
432 // Thread t = new Thread(WorkerProc);
433 // t.Name = "Thread" + i;
434 // t.Start();
435 // Thread.Sleep(30);
436 // }
437
438 //}
439
440 //static void WorkerProc()
441 //{
442 // for (int j = 0; j < 3;j++ )
443 // {
444 // semaphore.WaitOne();
445 // Console.WriteLine(Thread.CurrentThread.Name + ":Begin");
446 // Thread.Sleep(200);
447 // Console.WriteLine(Thread.CurrentThread.Name + ":End");
448 // semaphore.Release();
449 // }
450 //}
451 #endregion
452
453 #region ReaderWriterLock
454 //static int theResource = 0;
455 // static ReaderWriterLock rw1 = new ReaderWriterLock();
456 // static void Main()
457 // {
458 // Thread tr0 = new Thread(ThreadReader);
459 // Thread tr1 = new Thread(ThreadReader);
460 // Thread tw = new Thread(ThreadWriter);
461 // tr0.Start();
462 // tr1.Start();
463 // tw.Start();
464 // tr0.Join();
465 // tr1.Join();
466 // tw.Join();
467 // }
468
469 // static void ThreadReader()
470 // {
471 // for (int i = 0; i < 3;i++ )
472 // {
473 // try
474 // {
475 // rw1.AcquireReaderLock(1000);
476 // Console.WriteLine("Begin Read the Resource ={0}", theResource);
477 // Thread.Sleep(10);
478 // Console.WriteLine("End Read the resource ={0}", theResource);
479 // rw1.ReleaseLock();
480 // }
481 // catch (System.Exception e)
482 // {
483
484 // }
485 // }
486 // }
487
488 // static void ThreadWriter()
489 // {
490 // for (int i = 0; i < 3; i++)
491 // {
492 // try
493 // {
494 // rw1.AcquireWriterLock(1000);
495 // Console.WriteLine("Begin write the Resource ={0}", theResource);
496 // Thread.Sleep(100);
497 // theResource++;
498 // Console.WriteLine("End write the resource ={0}", theResource);
499 // rw1.ReleaseWriterLock();
500 // }
501 // catch (System.Exception e)
502 // {
503
504 // }
505 // }
506 // }
507 #endregion
508
509 #region SynchronizationAttribute.REQUIRED
510 //[Synchronization(SynchronizationAttribute.REQUIRED)]
511 //public class Foo: System.ContextBoundObject{
512 // public void DisplayThreadId()
513 // {
514 // Console.WriteLine("Begin:ManagedThreadId =" +
515 // Thread.CurrentThread.ManagedThreadId);
516 // Thread.Sleep(1000);
517 // Console.WriteLine("End: ManagedThreadId =" + Thread.CurrentThread.ManagedThreadId);
518 // }
519 //}
520
521 //static Foo m_Object = new Foo();
522 //static void Main()
523 //{
524 // Thread t0 = new Thread(ThreadProc);
525 // Thread t1 = new Thread(ThreadProc);
526 // t0.Start();
527 // t1.Start();
528 // t0.Join();
529 // t1.Join();
530
531 //}
532
533 //static void ThreadProc()
534 //{
535 // for (int i = 0; i < 2;i++ )
536 // {
537 // m_Object.DisplayThreadId();
538 // }
539 //}
540
541 #endregion
542
543 #region CurrentThread.ManagedThreadId
544
545 //public static void Main()
546 //{
547 // ThreadPool.RegisterWaitForSingleObject(
548 // new AutoResetEvent(false), new WaitOrTimerCallback(ThreadTaskWait), null, 2000, false);
549 // for (int count = 0; count < 3; ++count)
550 // {
551 // ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadTask), count);
552 // Thread.Sleep(12000);
553 // }
554
555
556 //}
557
558 //static void ThreadTask(object obj)
559 //{
560 // Console.WriteLine("Thread #{0} Task#{1} Begin", Thread.CurrentThread.ManagedThreadId, obj.ToString());
561 // Thread.Sleep(5000);
562 // Console.WriteLine("Thread #{0} Task#{1} End", Thread.CurrentThread.ManagedThreadId, obj.ToString());
563
564 //}
565
566 //static void ThreadTaskWait(object obj, bool signaled)
567 //{
568 // Console.WriteLine("Thread #{0} TaskWait", Thread.CurrentThread.ManagedThreadId);
569 //}
570 #endregion
571
572 #region 异步委托
573 //public delegate int Deleg(int a,int b);
574 //static int WriteSum(int a,int b)
575 //{
576 // int sum =a +b;
577 // Console.WriteLine("Thread #{0}:writeSum() sum ={1}",Thread.CurrentThread.ManagedThreadId,sum);
578 // return sum ;
579 //}
580
581 //static void Main()
582 //{
583 // Deleg proc = WriteSum;
584 // System.IAsyncResult async = proc.BeginInvoke(10, 10, null, null);
585 // int sum = proc.EndInvoke(async);
586 // System.Console.WriteLine("Thread#{0}:Main sum ={1}", Thread.CurrentThread.ManagedThreadId, sum);
587 //}
588 #endregion
589
590 #region 异步委托
591 public delegate int Deleg(int a, int b);
592 static AutoResetEvent ev = new AutoResetEvent(false);
593 static int WriteSum(int a, int b)
594 {
595 int sum = a + b;
596 Console.WriteLine("Thread #{0}:writeSum() sum ={1}", Thread.CurrentThread.ManagedThreadId, sum);
597 return sum;
598 }
599
600 static void SumDone(IAsyncResult async)
601 {
602 Thread.Sleep(1000);
603 Deleg proc = ((IAsyncResult)async).AsyncDelegate as Deleg;
604 int sum = proc.EndInvoke(async);
605 Console.WriteLine("Thread #{0}:callback method sum ={1}", Thread.CurrentThread.ManagedThreadId, sum);
606 ev.Set();
607 }
608
609 static void Main()
610 {
611 Deleg proc = WriteSum;
612 System.IAsyncResult async = proc.BeginInvoke(10, 10, null, null);
613 int sum = proc.EndInvoke(async);
614 System.Console.WriteLine("Thread#{0}:Main sum ={1}", Thread.CurrentThread.ManagedThreadId, sum);
615 }
616 #endregion
617 }
618 }
619
620