I have a problem returning an object that was created in other thread. The situation is this, my app need to send some request to remote server and wait an answer. In the main thread (1) i have a method called SendAndWait. This method put a message in a message queue for be sent and wait for an answer. Another thread (2) send the messages in the queue. A third thread (3) recieve messages and return to the main thread (1) the message with their answer.
This is my code.
Thread1:
void SendAndWait()
{
AutoResetEvent waitForAnswer = new AutoResetEvent(false);
int msgReferenceNumber = 1;
MyMessage msg;
// Register to wait for answer to the message with the number = msgReferenceNumber
RegisterToWait(msgNumber, waitForAnswer, ref msg);
// Send the request to the server, with the reference number.
SendRequest(msgReferenceNumber);
// Wait until the server send my answer
waitForAnswer.WaitOne();
// Now I have my answer. BUT I HAVE msg == null
MessageBox.Show(msg.Text);
}
Thread 2:
public class WhoWait
{
public int RefNumMsg;
public AutoResetEvent WaitForAnswer;
public MyMessage MessageWithAnswer;
}
// In this Dicctionary I save who wait for answers.
private Dictionary<int, WhoWait> Waiting = new Dictionary<WhoWait>();
void RegisterToWait(int msgRefNumber, AutoResetEvent waitForAnswer, ref msgWithAnswer)
{
WhoWait w = new WhoWait();
w.RefNumMsg = msgRefNumber;
w.WaitForAnswer = waitForAnswer;
w.MessageWithAnswer = msgWithAnswer;
Waiting.Add(msgRefNumber, w);
}
Thread3:
void OnRecieve()
{
// Get data from server
MyMessage msg = GetMessageData();
// Search for someone waiting for this answer
WhoWait w = Wainting[msg.RefNum];
// Set the response message
w.MessageWithAnswer = msg;
// Warn to the main thread. Message with their answer arrive
w.WaitForAnswer.Set();
}
The whole thing is working, except for the Message reference. When I read the object with I pass wich the ref key I have a null.
Can someone help me?
Thanks in advance.