Trouble with block access to resource

Hi.

I have a SerialPort with a GSM modem, i must send a SMS with AT command and wait a "OK" from the modem to know that the send is right.

SerialPort has a event that indicate data arrival, and i write a function to send AT commands to modem. I want send a AT command and lock the modem until receive a OK.

First i try:

DataArrival_Event()
{
lock(MySerialPort)
{
// Read Buffer & Proccess data
}
}
SendAT_Function()
{
lock(MySerialPort)
{
// Send the AT command.
}
}

But can do several calls followed to SendAT_Function and then DataArrival_Event receive a lot of "OK" in the same answer, i can't discern to as send corresponds each "OK".

After I try:

private Mutex MyMutex = new Mutex();
DataArrival_Event()

{

// Read Buffer & Proccess data
MyMutex.ReleaseMutex();

}
SendAT_Function()

{
MyMutex.WaitOne();

// Send the AT command.

}

Same problem. I monitorize the ThreadID and view that is always the same, this is the problem, of course.

After again, i try:

private Mutex MyMutex = new Mutex();

DataArrival_Event()

{

// Read Buffer & Proccess data

MyMutex.ReleaseMutex();

}
SendAT_LikeThread_Function() // <-- I call this function instead SendAT_Function
{
Thread NewThread = new Thread(new ThreadStart(SendAT_Function));
NewThread.Start();
}
SendAT_Function()

{

MyMutex.WaitOne();

// Send the AT command.

}

Now I get a AbandonedMutexException, because the NewThread leave the SendAT_Function without release the mutex.

I don't know more ways to do it :S

Same idea?

Regards.

[3698 byte] By [overpeer] at [2007-12-24]
# 1
I can't understand ur problem completely, but if u want to do some task in a new Thread and want that the main thread should wait till the task is complete u can use Delegate.BeginInvoke() and Delegate.EndInvoke().
singhhome at 2007-8-31 > top of Msdn Tech,Visual C#,Visual C# General...
# 2
singhhome wrote:
I can't understand ur problem completely,

I want send a AT command, and wait the OK or ERROR response from modem before send another AT command.

singhhome wrote:
but if u want to do some task in a new Thread and want that the main

thread should wait till the task is complete u can use

Delegate.BeginInvoke() and Delegate.EndInvoke().

humm ... i don't know how use it in this situation, some documentation link? Thanks.

Regards.

overpeer at 2007-8-31 > top of Msdn Tech,Visual C#,Visual C# General...
# 3

Who is going to invoke ur DataArrivalEvent() ? On which Thread its going to be invoked.

Threads can signal each other using AutoResetEvent. So ur Sent_AT() will send send AT signal and then do a AutoResetEvent().WaitOne, to get blocked till it gets a signal to continue further.

Ur DataArivalEvent() will send signal to Sent_AT(), by autoResetEvent.Signal().

singhhome at 2007-8-31 > top of Msdn Tech,Visual C#,Visual C# General...