Asynchronous task inside a loop in asp.net v4

I am using asp.net v4 C # and I have a list of email addresses. I want one of my administrators to be able to enter a message, click "SEND" and send emails one at a time.

Best way, in my opinion, to use async methods in .net? OnClick from the submit button, I take a list of email addresses, then call the async method. I just don't know how to get it to scroll through the list one by one and turn off the email.

You must complete one at a time so that I can save a copy of the letter sent against this user account.

Here is what I still have (cobblestone from textbooks / posts here)

protected void btnSend_Click(object sender, EventArgs e)
{
    //get a list of email addresses and send to them
    //these will come from the database once testing comp
    List<string> emails = new List<string>();
    emails.Add("test1@test.com");
    emails.Add("test2@test.com");
    emails.Add("test3@test.com");
    emails.Add("test4@test.com");
    emails.Add("test5@test.com");
    emails.Add("test6@test.com");
    emails.Add("test7@test.com");

    SendingDelegate worker = new SendingDelegate(DoSend);
    AsyncCallback completedCallback = new AsyncCallback(DoSendCompletedCallBack);

    lblThreadDetails.Text = "sending to " + emails.Count.ToString() + " email addresses";

    worker.BeginInvoke(completedCallback, AsyncOperationManager.CreateOperation(null));
    sending = true;

}

//boolean flag which indicates whether the async task is running
private bool sending = false;

private delegate bool SendingDelegate();

private bool DoSend()
{
    //send messages
    //emails sent here and saved in the DB each time

    //give the user some feed back on screen. X should be the email address.
    lblThreadDetails.Text = "processing " + x.ToString();
    Thread.Sleep(1000);
    return false;
}

private void DoSendCompletedCallBack(IAsyncResult ar)
{
    //get the original worker delegate and the AsyncOperation instance
    SendingDelegate worker = (SendingDelegate)((AsyncResult)ar).AsyncDelegate;

    //finish the asynchronous operation
    bool success = worker.EndInvoke(ar);
    sending = false;

    if (success)
    {
        //perform sql tasks now that crawl has completed
        lblThreadDetails.Text = "all done!";
    }
}

I basically need to put the async function call in a loop where I look at the list of email addresses.

?

+2
1

, ASP.NET 4.5 async/await, (. this ).

ASP 4.0 PageAsyncTask Page.RegisterAsyncTask. :

PageAsyncTask asyncTask = new PageAsyncTask(
    slowTask.OnBegin, slowTask.OnEnd, slowTask1.OnTimeout, 
    "AsyncTaskName", true);

worker.BeginInvoke/EndInvoke OnBegin/OnEnd. MSDN .

:

? .

, ,, .

-, , , , Thread.Sleep(1000) DoSend(). ( ).

: (, BeginInvoke) .

DoSend() , HTTP- ( btnSend_Click), BeginInvoke. , .

, , , IO/ API, . . , .

+2

Source: https://habr.com/ru/post/1526181/


All Articles