I have a console application which is having some functionality and I have a class doing some operation like publishing some message to a service. Now on each message publish on that class I am incrementing a counter.And I have a delegate associated to that counter, so that after a limit is reached I have a event on the Program.cs to block the call.Now I am doing the publish part async. So how to protect the counter property.
Below is my code:
Program.cs
var objMessageManager = new MessageManager();
objMessageManager.MaximumLimitToStopRequest += objMessageManager_MaximumLimitToStopRequest;
static void objMessageManager_MaximumLimitToStopRequest(object sender, int ItemCount)
{
if (ItemCount > Settings.MessageLimit)
{
Task.Delay(Settings.MessageDelayTime);
}
}
And below is the code for MessageManager.cs class
internal delegate void StopRequestEventHandler(object sender, int ProcessedItem);
public event StopRequestEventHandler MaximumLimitToStopRequest;
private int ProcessedItem;
private int noOfProcessed;
public int NoOfProcessed
{
get
{
return ProcessedItem;
}
private set
{
ProcessedItem = value;
if (MaximumLimitToStopRequest != null)
{
MaximumLimitToStopRequest(this, ProcessedItem);
}
}
}
And This is the code inside the method
internal async void CreateMessage(xyz sMessageObj)
{
try
{
await Task.Run(() =>
{
// Code to publish the message
});
Interlocked.Increment(ref noOfProcessed);
NoOfProcessed = noOfProcessed;
}
catch (Exception ex)
{
Log.Error("Exception occurred .", ex);
}
}
Please ignore naming mistake for variable and all. The application is running fine. I need help to make it thread safe for both reading and writing/incrementing NoOfProcessed property.