Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method Asynchronously?

Tags:

c#

winforms

I have created an application in windows form. Once I submit the application, the application get processed. I have created a class library which process the application and move the submitted application to different workflows. For this I have called the Class library from the click event of the Submit button. Everything is working fine, but the only problem is that once I submit the application and it calls the class library, it takes some time as it processes it. I want that the application should get closed and it calls the library method asynchronously. Below is the code:

private void OnPASubmit_Click(object sender, EventArgs e)
{
    if ((ApplAcct.AcctID == 0) || CheckForChanges())
    {
        UIHelper.ShowMessage("Please Save Application first");
        return;
    }
    try
    {
        if (!AOTHelper.ValidateCheckOut(ApplAcct.AcctID))
        {
            return;
        }
        WorkflowTask.PutAccountWorkflowTask(ApplAcct.AcctID, AOTHelper.FindAcctGUID(Main.objAccountGUID, Acct.AcctID), Environment.UserName, 2);
        AOTHelper.checkInAccount(ApplAcct.AcctID);
        AOTHelper.AccountToProcess(Acct.AcctID);
        UIHelper.ShowMessage("Application has been submitted for processing.");
        this.Close();
    }
    catch (Exception ex)
    {
         AOTHelper.WriteLog(ex, "Can not submit application for processing ");
    }

    // ...
}

The AotHelper.AccountToProcess(Acct.AcctID), method calls the class library and I want to do this with the help of Asunchronous calling so that the application doesn't have to wait for processing once it get submitted.

How will I do it. Please help!

like image 749
Running Rabbit Avatar asked Jul 01 '26 00:07

Running Rabbit


1 Answers

Multiple ways to run asynchronous, such as TPL, starting your own thread (and in the 4.5 framework await), but for winforms perhaps the easiest way is to add a BackGroundWorker component. You can just drag/drop one from the toolbox on your designer.

Double clicking the added component, automatically creates a method that catches the DoWork event of the backgroundworker, you can place your code there. Then in the submit button you only have to call

  backgroundWorker.RunWorkerAsync();
like image 104
Me.Name Avatar answered Jul 03 '26 14:07

Me.Name