0

I need to execute one method multiple time as async in c# with using the wait operator. following is my code

Task.Factory.StartNew(() => SentSMS(null, creation.SenderMobile, messageToSender));
Task.Factory.StartNew(() => SentSMS(null, creation.ReceiverMobile, messageToReciver));
Task.Factory.StartNew(() => SentSMS(null, empMobile, messageToEmp));
private async Task SentSMS(SMSReceived smsrecived, string mobilenumber ,string message)
{
    try
    {
        sent = new SMSSent();
        sent.MobileNumber = Util.ParseMobileNo(mobilenumber);
        sent.MobileOperator = Util.GetMobileOperator(mobilenumber);
        sent.QueryCodeId = 1;
        sent.ReplyByTelcoID = 1;
        sent.ReplyText = message;
        sent.ReplyByTelcoID = 1;
        sent.SMSReceivedId = (smsrecived == null ? 0 : smsrecived.ID);
        sent.SMSSentDate = DateTime.Now;
        sent.Status = 1;
        sentBL.Save(sent);
    }
    catch (Exception)
    {

    }
}

enter image description here The problem is , when the last request started , it override rest of 2 records. After execution of this code, i have checked in database it save one/same record 3 times.

do not tell me i am passing same data thrice. All the values are different. I need help. Let me know if i am lacking some where. I have also tried Task.Run(). I do not want to use await . In await , results are also same

Screenshot has attached of database

4
  • 3
    What does sent point to? I don't see it declared anywhere in the function so I assume it's a common variable inside the class? If so, it will in fact be replaced each time the function is invoked. You probably might want to declare it like this: var sent = new SMSSent(); and then return it at the end. Commented Oct 25, 2018 at 13:21
  • @Szab yes , sent is global variable . it declared at top Commented Oct 25, 2018 at 13:23
  • 4
    Clearly each task needs it's own sent. Commented Oct 25, 2018 at 13:23
  • @Igor i do not want to wait the main method. this SentSMS method must work async because i do not want any result Commented Oct 25, 2018 at 13:24

1 Answer 1

8

do not tell me i am passing same data thrice. All the values are different.

But they're not, because sent is a field, and it is being overwritten, and then all the values are the same.

Make sent a local created inside the method.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.