public static string GetHTMLFromURL(string url)
{
if(url.Length == 0)
throw new ArgumentException("Invalid URL","url");
string html = "";
HttpWebRequest request = GenerateGetOrPostRequest(url,"GET",null);
HttpWebResponse response = (HttpWebResponse)request.GetResponse( );
try
{
if(VerifyResponse(response)== ResponseCategories.Success)
{
// get the response stream.
Stream responseStream = response.GetResponseStream( );
// use a stream reader that understands UTF8
StreamReader reader = new StreamReader(responseStream,Encoding.UTF8);
try
{
html = reader.ReadToEnd( );
}
finally
{
// close the reader
reader.Close( );
}
}
}
finally
{
response.Close( );
}
return html;
}
class GradeBoard
{
// make a static ReaderWriterLock to allow all student threads to check
// grades and the instructor thread to post grades
static ReaderWriterLock readerWriter = new ReaderWriterLock( );
// the grade to be posted
static char studentsGrade = " ";
static void Main( )
{
// create students
Thread[] students = new Thread[5];
for(int i=0;i
{
students[i] = new Thread(new ThreadStart(StudentThreadProc));
students[i].Name = "Student " + i.ToString( );
// start the student looking for a grade
students[i].Start( );
}
// make those students "wait" for their grades by pausing the instructor
Thread.Sleep(5000);
// create instructor to post grade
Thread instructor = new Thread(new ThreadStart(InstructorThreadProc));
instructor.Name = "Instructor";
// start instructor
instructor.Start( );
// wait for instructor to finish
instructor.Join( );
// wait for students to get grades
for(int i=0;i
{
students[i].Join( );
}
}
static char ReadGrade( )
{
// wait ten seconds for the read lock
readerWriter.AcquireReaderLock(10000);
try
{
// now we can read safely
return studentsGrade;
}
finally
{
// Ensure that the lock is released.
readerWriter.ReleaseReaderLock( );
}
}
static void PostGrade(char grade)
{
// wait ten seconds for the write lock
readerWriter.AcquireWriterLock(10000);
try
{
// now we can post the grade safely
studentsGrade = grade;
Console.WriteLine("Posting Grade...");
}
finally
{
// Ensure that the lock is released.
readerWriter.ReleaseWriterLock( );
}
}
static void StudentThreadProc( )
{
bool isGradeFound = false;
char grade = " ";
while(!isGradeFound)
{
grade = ReadGrade( );
if(grade != " ")
{
isGradeFound = true;
Console.WriteLine("Student Found Grade...");
}
else // check back later
Thread.Sleep(1000);
}
}
static void InstructorThreadProc( )
{
// everyone likes an easy grader :)
PostGrade("A");
}
}
최신 콘텐츠