Lm th? no ? ?ng b? ha quy?n truy c?p vo m?t ngu?n l?c ?c chia s? trong m?t mi tr?ng a lu?ng b?ng cch s? d?ng Visual C#

D?ch tiu ? D?ch tiu ?
ID c?a bi: 816161 - Xem s?n ph?m m bi ny p d?ng vo.
Bung t?t c? | Thu g?n t?t c?

? Trang ny

TM T?T

B?n c th? th?c hi?n nhi?u nhi?m v? trong Microsoft Visual C# cc ?ng d?ng cng m?t lc b?ng cch s? d?ng a lu?ng. Multithreading c th? b?t ?u ch? ? khc nhau ? hon thnh nhi?m v? khc nhau cng m?t lc. Multithreading c?ng c?i thi?n hi?u su?t v ? p ?ng cc ?ng d?ng c?a b?n.

B?i v? nhi?u ch? ? c th? truy c?p m?t ngu?n l?c cng m?t lc, b?n c th? ?ng b? ha c nhn ch? ? v?i cc b? ph?n khc c?a chng tr?nh c?a b?n. Bi vi?t ny m t? m?t s? chung k?ch b?n v?i l?p tr?nh a lu?ng, v gi?i thch lm th? no ? ?ng b? ha cc truy c?p vo m?t ngu?n l?c ?c chia s? gi?a cc ch? ? c?a nhi?u.

Tr? gip ? b?o v? d? li?u ton c?u trong m-un trong m?t mi tr?ng Multithreaded

Cc l?nh v?c cng c?ng trong phng php c th? truy c?p t?t c? cc ch? ? ?ng d?ng c?a b?n. ? ?ng b? ha quy?n truy c?p vo cc l?nh v?c cng c?ng, b?n c th? s? d?ng ti s?n thay v? c?a l?nh v?c ny, v s? d?ng m?t ReaderWriterLock ?i t?ng ? ki?m sot quy?n truy c?p. thc hin vic nay, hay lam theo nhng bc sau:
  1. B?t ?u Microsoft Visual Studio.
  2. Trn cc Tp tr?nh n, i?m ?n M?i, sau b?m D an.
  3. Nh?p voVisual C# cc d? n d?i Cc lo?i d? n, v sau b?m Giao di?n i?u khi?n ?ng d?ng d?iKhun mu.

    Chu y Trong Visual Studio 2005 ho?c trong Visual Studio 2008, nh?p vo Visual C# d?i Cc lo?i d? n, v sau b?m Giao di?n i?u khi?n ?ng d?ng d?iKhun mu.
  4. Trong cc Tn h?p vn b?n, lo?iMultiThreadApplication, sau b?mOk.
  5. Thay th? m? hi?n c v?i o?n m? sau trong Class1.cs.

    Chu y Trong Visual Studio 2005 v trong Visual Studio 2008, t?p tin m?c ?nh l Program.cs.
    using System;
    using System.Threading;
    
    namespace MultiThreadApplication
    {
    	class Class1
    	{
    		private ReaderWriterLock rwl = new ReaderWriterLock();
    		private long myNumber;
    		public long Number   // the Number property
    		{
    			get
    			{
    				//Acquire a read lock on the resource.
    				rwl.AcquireReaderLock(Timeout.Infinite);                
    				try
    				{
    					Console.WriteLine("Thread:{0} starts getting the Number", Thread.CurrentThread.GetHashCode());
    					Thread.Sleep(50);
    					Console.WriteLine("Thread:{0} got the Number", Thread.CurrentThread.GetHashCode());
    
    				}
    				finally
    				{
    					//Release the lock.
    					rwl.ReleaseReaderLock();
    				}
    				return myNumber;
    			}
    			set
    			{
    				//Acquire a write lock on the resource.
    				rwl.AcquireWriterLock(Timeout.Infinite);
    				try
    				{
    					Console.WriteLine("Thread: {0} start writing the Number", Thread.CurrentThread.GetHashCode());
    					Thread.Sleep(50);
    					myNumber = value;
    					Console.WriteLine("Thread: {0} written the Number", Thread.CurrentThread.GetHashCode());
    				}
    				finally
    				{
    					//Release the lock.
    					rwl.ReleaseWriterLock();
    				}
    			}
    		}
    		
    		[STAThread]
    		static void Main(string[] args)
    		{
    			Thread []threadArray = new Thread[20]; 
    			int threadNum;
    
    
    			Class1 Myclass = new Class1();
    			ThreadStart myThreadStart = new ThreadStart(Myclass.AccessGlobalResource);
    
    			//Create 20 threads.
    			for( threadNum = 0; threadNum < 20; threadNum++)
    			{
    				threadArray[threadNum] = new Thread(myThreadStart);
    			}
    
    			//Start the threads.
    			for( threadNum = 0; threadNum < 20; threadNum++)
    			{   
    				threadArray[threadNum].Start();
    			}
    
    			//Wait until all the thread spawn out finish.
    			for( threadNum = 0; threadNum < 20; threadNum++)
    				threadArray[threadNum].Join();
    
    			Console.WriteLine("All operations have completed. Press enter to exit");
    			Console.ReadLine();
    		}
    
    		public void AccessGlobalResource()
    		{
    			Random rnd = new Random();
    			long theNumber;
    			
    			if (rnd.Next() % 2 != 0)
    				theNumber = Number;
    			else
    			{
    				theNumber = rnd.Next();
    				Number = theNumber;
    			}
    
    		}
    	}
    }
    
  6. Xy d?ng d? n, v sau ch?y cc ?ng d?ng.

Tr? gip ? lm cho l?p h?c c?a b?n Thread-Safe

Ch? ? c?a nhi?u c th? th? truy c?p vo m?t ?i t?ng cng m?t th?i gian. Khi nhi?u hn m?t thread c?nh tranh ? truy c?p vo m?t ?i t?ng cng lc , m?t s? ch? ? c th? nh?n ?c m?t nh n?c khng h?p l? n?u khc ch? ? s?a ?i cc ti nguyn cng m?t lc. V d?, n?u m?t thread l?n ?c l?nh v?c ?i t?ng trong khi ch? ? khc vi?c s?a ?i cc l?nh v?c, cc ch? ? ?u tin c th? nh?n tr?ng thi khng h?p l? c?a tr?ng. T?nh h?nh ny l tn l m?t i?u ki?n ch?ng t?c.

? trnh t?nh tr?ng ny, b?n c th? gip b?o v? ph?n quan tr?ng c?a m? c?a b?n t? i?u ki?n ch?ng t?c b?ng cch s? d?ng ? kha. M?t kha, ?i di?n b?i Visual C# t? kha kha tuyn b?, cho php m?t thread duy nh?t c?a th?c hi?n ? c ?c th?c hi?n ?c quy?n quy?n trn m?t ?i t?ng. Sau y V d? b?c ch?ng minh kha:
  1. M? ph?ng thu tr?c quan.
  2. Trn cc Tp tr?nh n, i?m ?n M?i, sau b?m D an.
  3. Nh?p voVisual C# cc d? n d?i Cc lo?i d? n, v sau b?m Giao di?n i?u khi?n ?ng d?ng d?iKhun mu.

    Chu y Trong Visual Studio 2005 ho?c trong Visual Studio 2008, nh?p vo Visual C# d?i Cc lo?i d? n, v sau b?m Giao di?n i?u khi?n ?ng d?ng d?iKhun mu.
  4. Trong cc Tn h?p vn b?n, lo?iMultiThreadLockApplication, sau b?mOk.
  5. Thay th? m? hi?n c v?i o?n m? sau trong Class1.CS:
    using System;
    using System.Threading;
    
    namespace MultiThreadLockApplication
    {
    	class Student
    	{
    		private static string myTeacherName = "Bill";
    		private string myName = "Grace";
    		private static object somePrivateStaticObject = new Object();
    
    		public static string TeacherName
    		{
    			get
    			{
    				string theName;
    
    				// Synchronize access to the shared member.
    				lock(somePrivateStaticObject)
    				{
    					Console.WriteLine("Thread {0} starts to get the teacher's name",Thread.CurrentThread.GetHashCode());
    					theName = myTeacherName;
    
    					// Wait for 0.3 second.
    					Thread.Sleep(300);
    					Console.WriteLine("Thread {0} finished to get the teacher's name:{1}.", Thread.CurrentThread.GetHashCode(), theName);
    				}
    				return theName;
    			}
    
    			set
    			{
    				lock(somePrivateStaticObject)
    				{
    					Console.WriteLine("Thread {0} starts to set the teacher's name.", Thread.CurrentThread.GetHashCode());
    					myTeacherName = value;
    
    					// Wait for 0.3 second.
    					Thread.Sleep(300);
    					Console.WriteLine("Thread {0} finished to set the teacher's name:{1}.", Thread.CurrentThread.GetHashCode(), value);
    				}
    			}
    		}
    
    		public string GetName()
    		{
    			string theName;
    			lock(this)
    			{
    				Console.WriteLine("Thread {0} starts to get the student's name.", Thread.CurrentThread.GetHashCode());
    				theName = myName;
    
    				// Wait for 0.3 second.
    				Thread.Sleep(300);
    				Console.WriteLine("Thread {0} finished to get the student's name:{1}", Thread.CurrentThread.GetHashCode(), theName);
    				return theName;
    			}
    		}
    
    		public string SetName(string NewName)
    		{
    			string theOldName;
    			lock(this)
    			{
    				Console.WriteLine("Thread {0} starts to set the student's name.", Thread.CurrentThread.GetHashCode());
    				theOldName = myName;
    				myName = NewName;
    
    				// Wait for 0.3 second.
    				Thread.Sleep(300);
    				Console.WriteLine("Thread {0} finished to set the student's name:{1}", Thread.CurrentThread.GetHashCode(), NewName);
    			}
    			return theOldName;
    		}
    	}
    
    	class Class1
    	{
    		public static int WorkItemNum = 20;
    		public static AutoResetEvent Done = new AutoResetEvent(false);
    
    		public static void AccessClassResource(object state)
    		{
    			Random rnd = new Random();
    			string theName;
    			Student AStudent = (Student) state;
    
    			if( (rnd.Next() %2) != 0)
    			{
    				if( (rnd.Next() %2) != 0)
    				{
    					switch (rnd.Next() %3 )
    					{
    						case 0:
    							Student.TeacherName = "Tom";
    							break;
    						case 1:
    							Student.TeacherName = "Mike";
    							break;
    						case 2:
    							Student.TeacherName = "John";
    							break;
    					}
    				}
    				else
    				{
    					theName = Student.TeacherName;
    				}
    			}
    			else
    			{
    				if( (rnd.Next() %2) != 0)
    				{
    					switch (rnd.Next() %3 )
    					{
    						case 0:
    							AStudent.SetName("Janet");
    							break;
    						case 1:
    							AStudent.SetName("David");
    							break;
    						case 2:
    							AStudent.SetName("Ben");
    							break;
    					}
    				}
    				else
    				{
    					theName = AStudent.GetName();
    				}
    			}
    
    			if(Interlocked.Decrement( ref WorkItemNum) == 0)
    			{
    				Done.Set();
    			}
    		}
    
    		[STAThread]
    		static void Main(string[] args)
    		{
    			int threadNum;
    			Student AStudent = new Student();
    
    			// Queue up 20 work items in the ThreadPool.
    			for (threadNum = 0 ; threadNum <= WorkItemNum -1 ; threadNum++) 
    			{
    				ThreadPool.QueueUserWorkItem(new WaitCallback(AccessClassResource),AStudent);
    			}
    
    			Done.WaitOne();
    			Console.WriteLine("All operations have completed. Press enter to exit");
    			Console.ReadLine();
    		}
    	}
    }
  6. Xy d?ng d? n, v sau ch?y cc ?ng d?ng.

THAM KH?O

? bi?t thm chi ti?t, xem cc sau cc trang Web c?a nh pht tri?n Microsoft m?ng (MSDN):
Ch? ? T?ng h?p
http://msdn2.Microsoft.com/en-US/Library/0ka9477y (vs.71) .aspx
ReaderWriterLock
http://msdn2.Microsoft.com/en-US/Library/bz6sth95 (vs.71) .aspx
ReaderWriterLock L?p h?c
http://msdn2.Microsoft.com/en-US/Library/System.Threading.readerwriterlock (vs.71) .aspx

Thu?c tnh

ID c?a bi: 816161 - L?n xem xt sau cng: 28 Thang Tam 2011 - Xem xt l?i: 2.0
p d?ng
  • Microsoft Visual C# 2008 Express Edition
  • Microsoft Visual C# 2005 Express Edition
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
T? kha:
kbthreadsync kbthread kbhowtomaster kbmt KB816161 KbMtvi
My d?ch
QUAN TRONG: Bi vi?t ny ?c d?ch b?ng ph?n m?m d?ch my c?a Microsoft ch? khng ph?i do con ng?i d?ch. Microsoft cung c?p cc bi vi?t do con ng?i d?ch v c? cc bi vi?t do my d?ch ? b?n c th? truy c?p vo t?t c? cc bi vi?t trong C s? Ki?n th?c c?a chng ti b?ng ngn ng? c?a b?n. Tuy nhin, bi vi?t do my d?ch khng ph?i lc no c?ng hon h?o. Lo?i bi vi?t ny c th? ch?a cc sai st v? t? v?ng, c php ho?c ng? php, gi?ng nh m?t ng?i n?c ngoi c th? m?c sai st khi ni ngn ng? c?a b?n. Microsoft khng ch?u trch nhi?m v? b?t k? s? thi?u chnh xc, sai st ho?c thi?t h?i no do vi?c d?ch sai n?i dung ho?c do ho?t ?ng s? d?ng c?a khch hng gy ra. Microsoft c?ng th?ng xuyn c?p nh?t ph?n m?m d?ch my ny.
Nh?p chu?t vo y ? xem b?n ti?ng Anh c?a bi vi?t ny:816161

Cung cp Phan hi

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com