Run code in a specific thread - c#

I have a console application which talks to an external library. Unfortunately all calls to the library must be made from the same thread.
How can I send method calls from one thread to another? (And, obviously, send the method results back to the calling thread.)
(No, this isn't to do with GUI programming. No, using the GUI message pump won't work.)
What I really want is for every single method on a particular class to always be executed in the same thread. But I have no idea how to do that.

My advice is to do what Windows Forms and WPF do to set up their single threaded message pumps - inherit SynchronizationContext. http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext%28v=vs.110%29.aspx
In your implementation, you will need to maintain a thread safe message queue, similar to this one:
http://www.codeproject.com/Articles/56369/Thread-safe-priority-queue-in-C
Your message pump worker thread will constantly check for new delegates, and invoke them.
So why not just write a message pump?
Well, by inheriting SynchronizationContext, you get all the CLR goodies like BackgroundWorker, AsyncOperationManager and the new await/async pattern keyword for free! They will all magically join back to your library thread.
Here is some code for a basic message pump. It does not implement SynchronizationContext:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace MessagePump
{
class Program
{
static void Main(string[] args)
{
MessagePump p = new MessagePump();
p.Start();
p.AddMessage(() => Console.WriteLine("message 1"));
p.AddMessage(() => Console.WriteLine("message 2"));
p.AddMessage(() => Console.WriteLine("message 3"));
Console.ReadLine();
p.Stop();
}
}
class MessagePump
{
bool m_Working = false;
Queue<Action> m_Actions = new Queue<Action>();
public void Start()
{
m_Working = true;
Thread t = new Thread(DoPump);
t.Name = "Message Pump Thread";
t.Start();
}
void DoPump()
{
while (m_Working)
{
try
{
Monitor.Enter(m_Actions);
while (m_Actions.Count > 0)
{
m_Actions.Dequeue()(); //dequeue and invoke a delegate
}
}
finally
{
Monitor.Exit(m_Actions);
}
Thread.Sleep(100); //dont want to lock this core!
}
}
public void Stop()
{
m_Working = false;
}
public void AddMessage(Action act)
{
lock (m_Actions)
{
m_Actions.Enqueue(act);
}
}
}
}

Related

How can I create a console application that utlilitize async/await

I'm creating a weather app that polls temperature from a service I've made:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Weather
{
class Program
{
static BackgroundWorker bgw;
static void Main(string[] args)
{
bgw = new BackgroundWorker();
bgw.DoWork += bgw_DoWork;
bgw.RunWorkerAsync();
}
static async void bgw_DoWork(object sender, DoWorkEventArgs e)
{
Weather bot = new Weather();
if (bot.IsRunning)
{
await bot.Update();
}
}
}
public class Weather
{
public bool IsRunning { get; set; }
private DateTime lastUpdated;
public Weather()
{
IsRunning = true;
lastUpdated = DateTime.Now.AddDays(-1);
}
public async Task<bool> Update()
{
if (lastUpdated < DateTime.Now)
{
lastUpdated = DateTime.Now.AddSeconds(30);
// temperature
double value = await GetLatestValue("New York");
}
return true;
}
private async Task<double> GetLatestValue(string city)
{
string url = "http://www" + city;
var client = new WebClient();
string data = await client.DownloadStringTaskAsync(url);
return 4.3;
}
}
}
The problem here is that it does not seem to work? The GetLatesValue function is just jibberish, will just return 4.3 for testing purposes.
What happens is that on await GetLatestValue the console application just quits.
The problem is simpler than you might think: you are running a BackgroundWorker, which basically wraps a thread that has .IsBackground = true. Such threads will not keep a process alive - they will be shut down automatically when the process exits. The process will exit when all non-background threads are completed.
Your Main method starts the BackgroundWorker, but then does nothing else - Main exits, and the application is complete. The BackgroundWorker is then shut down at whatever point it's reached. There's nothing wrong with the code it's running - but the app is shutting down without letting it complete.
EDIT: if you want to test this, simply put a Console.ReadLine() at the end of your Main - it'll keep the application alive until you press Enter, and so you should see your thread run until you do.
In addition to Dan Puzey's answer, there's not much sense in assigning an async void method as an event handler for BackgroundWorker, in the first place.
Your worker method bgw_DoWork will return and the background thread will be finished as soon as the execution point hits the first await inside bgw_DoWork. The bot.Update task most likely still will be pending at that point.
You don't need a BackgroundWorker here. The code can be as simple as this:
static void Main(string[] args)
{
DoWorkAsync().Wait();
}
static async Task DoWorkAsync()
{
Weather bot = new Weather();
if (bot.IsRunning)
{
await bot.Update();
}
}

Thread.Start not working

I am using the functions of the following class to invoke a messagebox. I am using thread.Start method to show the messagebox. The problem is it is not reaching to the respective function when thread.Start is called. Am i missing anything?
class MessageManager
{
string _message;
public MessageManager(string message)
{
_message = message;
}
public void ShowBigMessage()
{
Thread thread = new Thread(DisplayBigMessage);
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
// thread.Join();
}
public void ShowNormalMessage()
{
Thread thread = new Thread(DisplayNormalMessage);
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
//thread.Join();
}
private void DisplayBigMessage()
{
BigAppMessage appMessage = new BigAppMessage(_message);
appMessage.Show();
}
private void DisplayNormalMessage()
{
AppMessage appMessage = new AppMessage(_message);
appMessage.ShowDialog();
}
}
This is called inside a thread/delegate as below. I added this code into my program becuase it was raising
The calling thread must be STA, because many UI components require
this.
exception before
MessageManager message = new MessageManager("This is a test message.");
message.ShowBigMessage();
public partial class BigAppMessage : Window
{
public BigAppMessage(String message)
{
InitializeComponent();
myControl.setMessage(message); // mycontrol is just user control with a
//label on it
}
}
The Show() method requires a message loop. Fix:
private void DisplayBigMessage()
{
Application.Run(new BigAppMessage(_message));
}
There's already a message loop built into the ShowDialog() method. Using a thread to just display a window has no advantages, only problems.
In visual studio go to Debug->Exceptions and check the "thrown" box next to CLR exceptions. this will tell you where your problem is. Probably its a cross thread issue since you would ordinarily only interact with the UI on the UI thread.

Stopping an asynchronous stream outside of the AsyncCallback function

I've got a Stream object and I am using BeginRead to begin reading (obviously) into a buffer; the AsyncCallback function is called once the reading is complete. Within this function I can check if the user wants to get the next 'block' and start the BeginRead process again.
The problem I have is the user may choose to cancel while the stream is still reading (so before the AsyncCallback function is called), so how can I cancel the reading of the stream?
Just to further explain the issue - it seems I would have the same outcome if I use a BackgroundWorker with the Streams Read method or the asynchronous BeginRead method. The user could be left waiting for any length of time for the Read/BeginRead method to complete before I can check if the stream should stop reading.
Edit: The code below should do the job, I'm a million miles away from being anything decent in C# so it may well have a couple of bugs as I doubt it's perfect, although it does demonstrate the solution.
In brief, the CWorkManager manages a certain number of threads (which are held within a CWorkerDetail class). Each CWorkerDetail has a status, which can be EWaiting meaning the worker can be started, EReading which means the worker is reading from a source, during which time the worker can be stopped instantly, EWriting which saves the data that was read to the disk - this cannot be stoppped instantly and this process must complete before the thread is stopped. Finally there is EAborting which is set by the manager if the worker should be aborted as soon as possible; right now this is only set if the worker is in the middle of something which cannot be interrupted (such as writing to disk).
Right now, there isn't actually any reading or writing going on, as that would just complicate the main solution (which is basically just the StopWorker function checking a flag of CWorker to see if it can abort instantly); as such we simply cause the thread to sleep.
The GUI side is fairly simple with just a listbox (which shows the status of each worker) and a stop and start button. All code is below, hope this helps somebody, but as I say I'm not brilliant with C# so please watch out for bugs etc...
CWorkManager.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace ThreadApplication {
//A worker that spawns a number of threads (managed internally) that does nothing useful at all.
public class CWorkManager {
//The status of the worker.
public enum EWorkerStatus {
EWaiting,
EReading,
EWriting,
EAborting,
}
//Holds all data relevant to the worker.
private class CWorkerDetails {
//Simple variables.
private readonly Object _Lock=new Object();
private Thread gThread;
private EWorkerStatus gStatus;
private CWorkManager gParentInstance;
private int gIndex;
//Simple constructor.
public CWorkerDetails(int aIndex, CWorkManager aParentInstance, Thread aThread, EWorkerStatus aStatus) {
gIndex=aIndex;
gParentInstance=aParentInstance;
gThread=aThread;
gStatus=aStatus;
}
//Simple get set methods.
public Thread GetThread() { lock(_Lock) { return gThread; } }
public EWorkerStatus GetStatus() { lock(_Lock) { return gStatus; } }
//Sets the status and automatically updates the GUI.
public void SetStatus(EWorkerStatus aStatus) {
lock(_Lock) {
gStatus=aStatus;
Form1.gInstance.Invoke(new UpdateGUIDelegate(gParentInstance.UpdateGUI), new object[] { gIndex, GetStatus() });
}
}
}
//Worker variable.
private List<CWorkerDetails> gWorkers;
//Simple constructor.
public CWorkManager(int aWorkerCount){
gWorkers=new List<CWorkerDetails>();
for(int tIndex=0; tIndex<aWorkerCount; tIndex++)
gWorkers.Add(null);
}
//Creates and starts the worker.
public void StartWorker(int aWorkerIndex) {
//Create a new worker if there is none or if it is waiting to start.
if(gWorkers.ElementAt(aWorkerIndex)==null||gWorkers.ElementAt(aWorkerIndex).GetStatus()==EWorkerStatus.EWaiting)
gWorkers[aWorkerIndex]=new CWorkerDetails(aWorkerIndex, this, new Thread(new ParameterizedThreadStart(WorkerMethod)), EWorkerStatus.EWaiting);
//If the worker is waiting to start, then start.
if(gWorkers.ElementAt(aWorkerIndex).GetStatus()==EWorkerStatus.EWaiting)
gWorkers.ElementAt(aWorkerIndex).GetThread().Start(gWorkers.ElementAt(aWorkerIndex));
}
//Stops the worker.
public void StopWorker(int aWorkerIndex) {
//Do nothing if the worker is null.
if(gWorkers.ElementAt(aWorkerIndex)==null)
return;
//Do nothing if the worker is waiting.
if(gWorkers.ElementAt(aWorkerIndex).GetStatus()==EWorkerStatus.EWaiting)
return;
//If the worker is reading we can abort instantly.
if(gWorkers[aWorkerIndex].GetStatus()==EWorkerStatus.EReading) {
gWorkers[aWorkerIndex].GetThread().Abort();
gWorkers[aWorkerIndex].SetStatus(EWorkerStatus.EWaiting);
return;
}
//Since the worker is not reading or waiting, we have to request the
//worker to abort by itself.
gWorkers[aWorkerIndex].SetStatus(EWorkerStatus.EAborting);
}
//Updates the GUI.
private delegate void UpdateGUIDelegate(int aIndex, EWorkerStatus aStatus);
private void UpdateGUI(int aIndex, EWorkerStatus aStatus) {
Form1.gInstance.SetThreadStatus(aIndex, aStatus);
}
//This method is where all the real work happens.
private void WorkerMethod(Object aWorker) {
//Fetch worker.
CWorkerDetails mWorker=(CWorkerDetails)aWorker;
//Loop forever, the thread will exit itself when required.
while(true) {
//Is the worker status aborting - if so we stop here.
if(mWorker.GetStatus()==EWorkerStatus.EAborting) {
mWorker.SetStatus(EWorkerStatus.EWaiting);
return;
}
//This would normally be reading from a stream which would cause the thread
//to block, simulate this by just sleeping the thread.
mWorker.SetStatus(EWorkerStatus.EReading);
Thread.Sleep(3000);
//Is the worker status aborting - if so we stop here.
if(mWorker.GetStatus()==EWorkerStatus.EAborting) {
mWorker.SetStatus(EWorkerStatus.EWaiting);
return;
}
//All data has been read, set status to writing and again simulate by
//sleeping the thread.
mWorker.SetStatus(EWorkerStatus.EWriting);
Thread.Sleep(3000);
}
}
}
}
Form1.cs:
Contains:
A List box (ListBox_WorkerStatus)
A button (Button_Start)
A button (Button_Stop)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ThreadApplication {
public partial class Form1:Form {
public static Form1 gInstance;
private CWorkManager gManager;
public Form1() {
InitializeComponent();
Button_Start.Click+=new EventHandler(Button_Start_Click);
Button_Stop.Click+=new EventHandler(Button_Stop_Click);
gInstance=this;
for(int tIndex=0; tIndex<5; tIndex++)
ListBox_WorkerStatus.Items.Add("Created");
gManager=new CWorkManager(ListBox_WorkerStatus.Items.Count);
}
public void SetThreadStatus(int aIndex, CWorkManager.EWorkerStatus aStatus) {
ListBox_WorkerStatus.Items[aIndex]=aStatus.ToString();
}
private void Button_Start_Click(object sender, EventArgs e) {
if(ListBox_WorkerStatus.SelectedIndex>=0) {
gManager.StartWorker(ListBox_WorkerStatus.SelectedIndex);
}
}
private void Button_Stop_Click(object sender, EventArgs e) {
if(ListBox_WorkerStatus.SelectedIndex>=0) {
gManager.StopWorker(ListBox_WorkerStatus.SelectedIndex);
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
for(int tIndex=0; tIndex<ListBox_WorkerStatus.Items.Count; tIndex++) {
gManager.StopWorker(tIndex);
}
}
}
}
Please Take look atCancel BeginRead this
Use BackgroundWorker
BackgroundWorker backgroundWorker1= new backgroundWorker()
private void InitializeBackgroundWorker()
{
backgroundWorker1.DoWork +=
new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.WorkerSupportsCancellation = true;
}
private void backgroundWorker1_DoWork(object sender,
DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
e.Result = YourWorkToDo();
}
public void Start()
{
backgroundWorker1.RunWorkerAsync()
}
public voic Cancel()
{
backgroundWorker1.CancelAsync();
{
If you want more help leave comment

WPF Dispatcher and Running it in background

I tried to wrap the dispatcher in a thread. But the result is not what i expect. How can i solve that problem?
public void Start()
{
ThreadStart ts = inner;
Thread wrapper = new Thread(ts);
wrapper.Start();
}
private void inner()
{
_Runner.Dispatcher.Invoke(_Runner.Action, DispatcherPriority.Normal);
}
You have not shown us enough code/explained yourself well enough to be able to provide a good answer, but I'm guessing your action (_Runner.Action) is expensive and slow to execute. If so, that is why your UI is unresponsive. You're essentially telling the Dispatcher to run that expensive operation on the UI thread when what you really want to do is run as much of your operation on the background thread as possible, and then marshal back to the UI thread via the Dispatcher only when necessary.
When you fire an action through/on the dispatcher, that action is called on the UI thread.
My guess is that you are doing the work/processing in the _Runner.Action function and it is tying up the UI thread. You'll have to do the main processing part in the inner() function and then call the Dispatcher for the final update details.
If you absolutely must process on the dispatcher, break your process into smaller pieces and call Dispatcher.BeginInvoke() for each piece so other events can be processed in between your process.
You need to break Runner.Action into two parts - the long running part that does the calculation and the part that updates the GUI.
After you do that you call the long running part in the background thread and use the dispatcher only on the UI update part.
By the way, you should also probably use BeginInvoke and not Invoke.
If the long running part of Runner.Action is updating the GUI than you can't use a background thread to solve your problem - there are solutions for slow GUI operations but they change depending on what exactly you are trying to do.
Here is an example that will let you run WPF applications with multiple UI threads. I believe this will help you. Refer to this http://eprystupa.wordpress.com/2008/07/28/running-wpf-application-with-multiple-ui-threads/
Thread lThread = new Thread(() =>
{
var lWnd = new Window1();
lWnd.Show();
lWnd.Closed += (sender2, e2) => lWnd.Dispatcher.InvokeShutdown();
System.Windows.Threading.Dispatcher.Run();
});
lThread.SetApartmentState(ApartmentState.STA);
lThread.Start();
Ditto what everyone here has said.
Additionally, you may want to look into using the BackgroundWorker class.
This is what I have started using for background tasks... I have not been using it long, so I don't know if there are bugs.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SSA.Utility
{
public class BackgroundTaskManager : IDisposable
{
private System.Windows.Threading.Dispatcher _OwnerDispatcher;
private System.Windows.Threading.Dispatcher _WorkerDispatcher;
private System.Threading.Thread _WorkerThread;
private Boolean _WorkerBusy;
private System.Threading.EventWaitHandle _WorkerStarted = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset);
public BackgroundTaskManager()
{
_OwnerDispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
_WorkerThread = new System.Threading.Thread(new System.Threading.ThreadStart(WorkerStart));
_WorkerThread.Name = "BackgroundTaskManager:" + DateTime.Now.Ticks.ToString();
_WorkerThread.IsBackground = true;
_WorkerThread.Start();
_WorkerStarted.WaitOne();
}
public Boolean IsBusy
{
get { return _WorkerBusy; }
}
public System.Windows.Threading.Dispatcher Dispatcher
{
get {
return _WorkerDispatcher;
}
}
public System.Windows.Threading.Dispatcher OwnerDispatcher
{
get
{
return _OwnerDispatcher;
}
}
private void WorkerStart()
{
_WorkerDispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
_WorkerDispatcher.Hooks.DispatcherInactive += WorkDone;
_WorkerDispatcher.Hooks.OperationPosted += WorkAdded;
_WorkerStarted.Set();
System.Windows.Threading.Dispatcher.Run();
}
private void WorkAdded(Object sender, System.Windows.Threading.DispatcherHookEventArgs e)
{
_WorkerBusy = true;
}
private void WorkDone(Object sender, EventArgs e)
{
_WorkerBusy = false;
}
public void Dispose()
{
if (_WorkerDispatcher != null)
{
_WorkerDispatcher.InvokeShutdown();
_WorkerDispatcher = null;
}
}
}
}
// Useage (not tested)
private SSA.Utility.BackgroundTaskManager _background = new SSA.Utility.BackgroundTaskManager();
public void LongTaskAsync()
{
_background.Dispatcher.BeginInvoke(new Action(LongTask), null);
}
public void LongTask()
{
System.Threading.Thread.Sleep(10000); // simulate a long task
_background.OwnerDispatcher.BeginInvoke(new Action<STATUSCLASS>(LongTaskUpdate), statusobject);
}
public void LongTaskUpdate(STATUSCLASS statusobject) {
}
Yes. _Runner.Action is the problem. Some long-timed methods used in the Dispatcher block. But solution is "dont use the any thread not related to UI in the dispatcher"

Sample code to illustrate a deadlock by using lock(this)

I've read several articles and posts that say that lock(this), lock(typeof(MyType)), lock("a string") are all bad practice because another thread could lock on the same key and cause a deadlock. In order to understand this problem, I was trying to create some sample code to illustrate the deadlock but have been unable to wrap my head around this.
Can someone write a concise bit of code that illustrates this classic problem? Please keep it short, I can digest code in smaller chunks only.
Edit:
I think lassevk sums it up well; that the real problem is that you have lost control over your locks. Once that happens, you cannot control the order the locks are called, and you are allowing a potential deadlock situation.
lock(this), lock(typeof(MyType)), etc all are situations where you have chosen a lock that is impossible to control.
A deadlock will only occur if you have more than one lock. You need a situation where both threads hold a resource that the other needs (which means there has to be a least two resources, and the two threads have to attempt to acquire them in a different order)
So a simple example:
// thread 1
lock(typeof(int)) {
Thread.Sleep(1000);
lock(typeof(float)) {
Console.WriteLine("Thread 1 got both locks");
}
}
// thread 2
lock(typeof(float)) {
Thread.Sleep(1000);
lock(typeof(int)) {
Console.WriteLine("Thread 2 got both locks");
}
}
Assuming both threads are started within a second of each others, they will both have time to grab the first lock before anyone gets to the inner lock. Without the Sleep() call, one of the threads would most likely have time to get and release both locks before the other thread even got started.
The idea is that you should never lock on something you cannot control who has access to.
Type objects are singletons visible to every .net piece of code and you cannot control who locks on your "this" object from the outside.
Same thing is for strings: since strings are immutable, the framework keeps just one instance of "hard coded" strings and puts them in a pool (the string is said to be interned), if you write two times in your code the string "hello", you will always get the same abject.
Consider the following example: you wrote just Thread1 in your super private call, while Thread2 is called by some library you are using in a background thread...
void Thread1()
{
lock (typeof(int))
{
Thread.Sleep(1000);
lock (typeof(long))
// do something
}
}
void Thread2()
{
lock (typeof(long))
{
Thread.Sleep(1000);
lock (typeof(int))
// do something
}
}
Sure, here you go.
Note that the common example for a deadlock is when you acquire multiple locks, and two or more threads end up waiting for each other.
For instance, two threads that locks like this:
Thread 1 Thread 2
Lock "A" Lock "B"
Lock "B" Lock "A" <-- both threads will stop dead here
waiting for the lock to be come
available.
However, in this example I didn't bother with that, I just let one thread lock indefinitely. You really don't want to loose control over your locks, so while this is a contrived example, the fact that the background thread can completely block the main thread like this, is bad.
using System;
using System.Threading;
namespace ConsoleApplication7
{
public class Program
{
public static void Main(string[] args)
{
LockableClass lockable = new LockableClass();
new Thread(new ParameterizedThreadStart(BackgroundMethod)).Start(lockable);
Thread.Sleep(500);
Console.Out.WriteLine("calling Reset");
lockable.Reset();
}
private static void BackgroundMethod(Object lockable)
{
lock (lockable)
{
Console.Out.WriteLine("background thread got lock now");
Thread.Sleep(Timeout.Infinite);
}
}
}
public class LockableClass
{
public Int32 Value1 { get; set; }
public Int32 Value2 { get; set; }
public void Reset()
{
Console.Out.WriteLine("attempting to lock on object");
lock (this)
{
Console.Out.WriteLine("main thread got lock now");
Value1 = 0;
Value2 = 0;
}
}
}
}
This is pretty standard bad-ness. Grabing the locks out of order and then sleeping with the lock. Two bad things to do. :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace DeadLock
{
public class Program
{
static void Main(string[] args)
{
var ddt = new DontDoThat();
ddt.Go();
}
}
public class DontDoThat
{
private int _badSharedState = 0;
private readonly object _lock1 = new object();
private readonly object _lock2 = new object();
public void Go()
{
new Thread(BadGuy1).Start();
new Thread(BadGuy2).Start();
Console.WriteLine("Leaving Go!");
}
public void BadGuy1()
{
lock (_lock1)
{
Thread.Sleep(100); // yeild with the lock is bad
lock (_lock2)
{
_badSharedState++;
Console.Write("From Bad Guy #1: {0})", _badSharedState );
}
}
}
public void BadGuy2()
{
lock (_lock2)
{
lock (_lock1)
{
_badSharedState++;
Console.Write("From Bad Guy #2: {0})", _badSharedState);
}
}
}
}
}
The problem is that lock("a string") is locking on a singleton. This means that other objects that use the same lock could be an infinite wait.
for example:
using System;
using System.Threading;
namespace ThreadLock
{
class Program
{
static void Main(string[] args)
{
lock ("my lock")
{
ManualResetEvent evt = new ManualResetEvent(false);
WorkerObject worker = new WorkerObject(evt);
Thread t = new Thread(new ThreadStart(worker.Work));
t.Start();
evt.WaitOne();
}
}
}
class WorkerObject
{
private ManualResetEvent _evt;
public WorkerObject(ManualResetEvent evt)
{
_evt = evt;
}
public void Work()
{
lock ("my lock")
{
Console.WriteLine("worked.");
_evt.Set();
}
}
}
}
In this case, the calling code creates a lock on a string then makes a worker object. The worker object in Work() locks on the same string, which is a singleton in C#. It ends up in deadlock because the caller owns the lock and is waiting for a signal which will never come.
class Character
{
public Character Other;
public string Name;
private object locker = new object();
public Character(string name)
{
Name = name;
}
public void Go()
{
lock (locker)
{
Thread.Sleep(1000);
Console.WriteLine("go in {0}", Name);
Other.Go();
}
}
}
class Program
{
static void Main(string[] args)
{
Character a = new Character("A");
Character b = new Character("B");
a.Other = b;
b.Other = a;
new Thread(a.Go).Start();
b.Go();
Console.ReadLine();
}
}

Categories

Resources