Currently I'm working on widows service which is receiving messages from local private MSMQ. Queue is transactional.
Receiving is done like that:
public void ReceiveAndSaveData(MessageQueue queue, MsmqDbContext context)
{
var message = new Message();
try
{
using (var tx = new MessageQueueTransaction())
{
tx.Begin();
message = queue.Receive(tx);
var bodyReader = new StreamReader(message.BodyStream);
var jsonBody = bodyReader.ReadToEnd();
var messageData = JsonConvert.DeserializeObject<QueueMessage>(jsonBody);
/*THERE IS SOME DATA PROCESSING*/
tx.Commit();
}
}
catch (JsonSerializationException e)
{
Logger.WriteError(new LogDetail("Error occured during deserializing incoming data.", e, message.Id));
}
catch (Exception e)
{
Logger.WriteError(new LogDetail("Error occured during saving data to database", e, message.Id));
}
}
In case of JsonSerializationException, I want to delete this message from current queue. Does anybody know how to solve this problem?
Use the Abort()
method and also move the tx-object creation outside the try-catch block.
public void ReceiveAndSaveData(MessageQueue queue, MsmqDbContext context)
{
bool exceptionOccurred = false;
var message = new Message();
MessageQueueTransaction tx;
try
{
exceptionOccurred = false;
using (tx = new MessageQueueTransaction())
{
tx.Begin();
message = queue.Receive(tx);
var bodyReader = new StreamReader(message.BodyStream);
var jsonBody = bodyReader.ReadToEnd();
var messageData = JsonConvert.DeserializeObject<QueueMessage>(jsonBody);
/*THERE IS SOME DATA PROCESSING*/
}
}
catch (JsonSerializationException e)
{
Logger.WriteError(new LogDetail("Error occured during deserializing incoming data.", e, message.Id));
tx.Abort(); //Rolls back the pending internal transaction
exceptionOccurred = true;
}
catch (Exception e)
{
Logger.WriteError(new LogDetail("Error occured during saving data to database", e, message.Id));
exceptionOccurred = true;
}
finally
{
if(!exceptionOccurred)
tx.Commit();
}
}
把tx.Commit()
也在里面catch
了块JsonSerializationException
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.