How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#?

You want the lock statement, which is the same as Monitor Enter/Exit:

lock(obj)

{

// code

}

translates to: try

{

CriticalSection.Enter(obj);

// code

}

finally

{

CriticalSection.Exit(obj);

}

Showing Answers 1 - 4 of 4 Answers

ans:

yes,it is right.

lock statement, which is the same as Monitor Enter/Exit:

lock(obj)

{

// code

}

translates to: try

{

CriticalSection.Enter(obj);

// code

}

finally

{

CriticalSection.Exit(obj);

}

  Was this answer useful?  Yes

jaganmohan2

  • Apr 18th, 2007
 

A thread is simply a separate stream of execution that takes place simultaneously

with and independently of everything else that might be happening.

A thread can synchronize itself with another thread waiting for it to complete.

The System.Threading.Thread class has an instance member called Join that can provide this type of functionality.

 Sample

using System.Threading;

private void DoSomething()

{

//DO Something

}

 

public static void Main(string[] args)

{

ThreadStart threadStart = new ThreadStart(DoSomething);

Thread myThread = new Thread(threadStart);

myThread.Start();

//Wait for the thread to finish

myThread.Join();

//Do Something Else

}

 

using System.Threading;

using System.IO;

private void DoSomething()//DoSomething(int Param)

{

Monitor.Enter(Writer);

Writer.WriteLine("Hello");

Monitor.Exit(Writer);

}

  

//Global Definition

ThreadStart threadStart = new ThreadStart(DoSomething);

//ParameterizedThreadStart threadStart = new ParameterizedThreadStart(DoSomething);

Thread myThread = new Thread(threadStart);

//Common Resource

StreamWriter Writer = File.CreateText("Sample.txt");

  

public static void Main(string[] args)

{

myThread.Start();

//myThread.Start(100);

//Wait for the thread to finish

myThread.Join();

//Do Something Else

}

using System.Threading;

private void DoSomething()

{

//DO Something

}

 

public delegate void DELEGATE();

 

public static void Main(string[] args)

{

DELEGATE test = new DELEGATE(DoSomething);

AsyncCallback callback = new AsyncCallback(CALLBACK);

IAsyncResult result = test.BeginInvoke(callback, null);

}

 

public void CALLBACK(IAsyncResult result)

{

}

 

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions