i have a console applicaiton . in this application i make contact with a queue. first i check to see if for example queue with name 'exampleQueue' exists or not. and if it does not exist i create it. after creating and returing the path or just returning the path . i want to attach the ReceiveCompleted event to this queue. i have two approach i can use 'using' keyword to make the queue dispoed after my work or i can just use normal way to create queue object .
in below u can see my code :
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
CreateQueue(".\\exampleQueue", false);
using (var queue = new MessageQueue(".\\exampleQueue"))
{
queue.ReceiveCompleted += MyReceiveCompleted;
queue.BeginReceive();
}
}
public static void CreateQueue(string queuePath, bool transactional)
{
if (!MessageQueue.Exists(queuePath))
{
MessageQueue.Create(queuePath, transactional);
}
else
{
Console.WriteLine(queuePath + " already exists.");
}
}
private static void MyReceiveCompleted(Object source,
ReceiveCompletedEventArgs asyncResult)
{
var queue = (MessageQueue)source;
try
{
var msg = queue.EndReceive(asyncResult.AsyncResult);
Console.WriteLine("Message body: {0}", (string)msg.Body);
queue.BeginReceive();
}
catch (Exception ex)
{
var s = ex;
}
finally
{
queue.BeginReceive();
}
return;
}
}
}
the problem that i face is that whenever i use this code for create queue object
using (var queue = new MessageQueue(".\\exampleQueue"))
{
queue.ReceiveCompleted += MyReceiveCompleted;
queue.BeginReceive();
}
the MyReceiveCompleted event does not work properly . but when i use this
var queue = new MessageQueue(".\\exampleQueue");
queue.ReceiveCompleted += MyReceiveCompleted;
queue.BeginReceive();
every thing just work in proper way.
my question is that which approcah is the best one ? and if i choose to use the first approcah , how can i make it work ?
accept my apologize for bad typing .