The BackgroundWorker class allows you to run an operation on a separate,
dedicated thread. Time-consuming operations like downloads and database
transactions can cause your user interface (UI) to seem as though it has stopped
responding while they are running. When you want a responsive UI and you are
faced with long delays associated with such operations, the BackgroundWorker
class provides a convenient solution.
To execute a time-consuming operation in the background, create a
BackgroundWorker and listen for events that report the progress of your
operation and signal when your operation is finished. You can create the
BackgroundWorker programmatically or you can drag it onto your form from the
Components tab of the Toolbox. If you create the BackgroundWorker in the Windows
Forms Designer, it will appear in the Component Tray, and its properties will be
displayed in the Properties window.
To set up a background operation, add an event handler for the DoWork event.
Call your time-consuming operation in this event handler. To start the
operation, call RunWorkerAsync. To receive notifications of progress updates,
handle the ProgressChanged event. To receive a notification when the operation
is completed, handle the RunWorkerCompleted event.
Enough of this theory, we'll go into the example just for testing purpose I've
created a small but effective example. Following is the design code for the
same.
Since background worker will create a different thread for executing the code of
ours ie we can say that the code will be executed in an asynchronous manner, so
we need to define the Async property of our page to true.
- <%@ Page Language="C#" AutoEventWireup="true" Async="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head runat="server">
- <title>Untitled Page</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Send Mail" /></div>
- </form>
- </body>
- </html>
Following is the source code for the same.
- using System;
- using System.Data;
- using System.Configuration;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Web.UI.HtmlControls;
- using System.ComponentModel;// for backgroundworker class
- using System.Net;
- using System.Net.Mail;
- using System.Threading;
- public partial class _Default : System.Web.UI.Page
- {
- BackgroundWorker bw;
- protected void Page_Load(object sender, EventArgs e)
- {
- bw = new BackgroundWorker();
- bw.DoWork+=new DoWorkEventHandler(bw_DoWork);
- bw.WorkerSupportsCancellation = true;
- bw.WorkerReportsProgress = false;
- }
- public void SendMail()
- {
- MailMessage msg = new MailMessage();
- msg.From = new MailAddress("[email protected]");
- msg.To.Add("[email protected]");
- msg.Body = "Testing the automatic mail";
- msg.IsBodyHtml = true;
- msg.Subject = "Movie Data";
- SmtpClient smt = new SmtpClient("smtp.gmail.com");
- smt.Port = 587;
- smt.Credentials = new NetworkCredential("Your Gmail Id", "Your Password");
- smt.EnableSsl = true;
- smt.Send(msg);
- string script = "<script>alert('Mail Sent Successfully');self.close();</script>";
- this.ClientScript.RegisterClientScriptBlock(this.GetType(), "sendMail", script);
- }
- public void bw_DoWork(object sender, DoWorkEventArgs e)
- {
- SendMail();
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- DateTime current_time = DateTime.Now;
- current_time = current_time.AddSeconds(10);
- Thread.Sleep(10000);
- if (current_time == DateTime.Now)
- {
- bw.RunWorkerAsync();
- }
- }
- }
In this code after the user clicks the button the mail will be send
automatically after 10 seconds to the specified email id.
Following is the output for the same.



Gerard Matthew GodoyPosted Aug 29, 2018, 6:35 AM
How about SMS instead of email send help!
Gerard Matthew GodoyPosted Aug 29, 2018, 6:08 AM
Office Api is for?? please help
Gerard Matthew GodoyPosted Aug 29, 2018, 6:07 AM
What is the purpose of downloading OFFICE API?????
bavithra nPosted Jan 25, 2017, 8:33 AM
I want this example, A mail should deliver to Manager when the product date will expire after 10 days.
Miyulu RasanjalaPosted Oct 7, 2016, 6:24 AM
Hi. Thank you very much for the post. It was working for me. But then it stopped. The emails aren't going through but I don't get any error messages or the successful message? Any suggestions please?
Mukesh MouryaPosted Mar 28, 2016, 3:26 AM
Dear Sir, Code is working Fine in Local but when it uploaded on web it throws an exception , How can i resolve this problem.
Karthikeyan KPosted Aug 10, 2015, 8:41 AM
Nice one but ??
Omid NasriPosted Nov 7, 2014, 3:38 PM
thank you for article but this sample is not best code
mahesh chindhePosted Mar 28, 2014, 1:19 AM
Hi, I am new to .NET and trying to run your code. I made some relevant change like email-id but it's not throw any error and popup window viz Mail send successfully. Please help me out. Thanks in advance
venkat reddyPosted Aug 19, 2013, 7:02 AM
its working very very thanks for your code
tejas shyaniPosted Jul 31, 2013, 2:46 AM
Not Working MANNNNNNNNNNNN!!!
Vishal GilbilePosted Jun 26, 2013, 1:21 AM
else look at the below link http://www.c-sharpcorner.com/uploadfile/17e8f6/sending-automatic-mail-through-Asp-Net/
Vishal GilbilePosted Jun 26, 2013, 1:21 AM
Hi aarti in the button click event we've declare currentTime as the DateTime variable in which we have added 10 seconds to the Current Time and by using Thread.sleep function we are holding the execution of the Thread to 10 seconds by putting value in the Sleep methods as 100000 after the CurrentTime and The DateTime.Now value will be same and the condition will be satisified Hope it helps you
Aarthi SekarPosted Jun 25, 2013, 4:30 AM
It kills my time. dont try the above one
Aarthi SekarPosted Jun 25, 2013, 4:25 AM
if (current_time == DateTime.Now) This time is everytime false and its not going inside. here is some prblem
Aarthi SekarPosted Jun 25, 2013, 4:25 AM
Project does not work properly
Vishal GilbilePosted Jun 18, 2013, 6:49 AM
else look at the below link http://www.c-sharpcorner.com/uploadfile/17e8f6/sending-automatic-mail-through-Asp-Net/
Vishal GilbilePosted Jun 18, 2013, 6:47 AM
Hi Yogesh in the button click event we've declare currentTime as the DateTime variable in which we have added 10 seconds to the Current Time and by using Thread.sleep function we are holding the execution of the Thread to 10 seconds by putting value in the Sleep methods as 100000 after the CurrentTime and The DateTime.Now value will be same and the condition will be satisified Hope it helps you
Yogesh Singh RawatPosted Jun 18, 2013, 3:28 AM
Hi Vishal I am stucking at this part if (current_time == DateTime.Now) This time is everytime false and its not going inside if.can you help me
Yogesh Singh RawatPosted Jun 18, 2013, 3:26 AM
DateTime current_time = DateTime.Now;
anil babuPosted May 8, 2013, 6:42 AM
Thank you, I want to send mail automatically every day using asp.net
Vishal GilbilePosted Mar 8, 2013, 3:26 AM
It works on local server also just check your internet connection and still if you are facing any problem kindly download the code.
Amitesh VermaPosted Mar 8, 2013, 1:38 AM
this doesnt work on local server??? error is : The server response was: 5.5.1 Unrecognized command. kv6sm5113414pab.13 - gsmtp
maria louisaeditedPosted Feb 27, 2013, 6:54 AMEdited Feb 28, 2013, 9:51 PM
Hi, I want to use this in registration coding but its not working. Can you help me over that. Thanks in advance.
Vishal GilbilePosted Feb 16, 2013, 6:45 AM
the above code is quite updated, even if its not working just check whether you have added the no of seconds or minutes or hours to your current_time date object or else download the entire code that will do help you with your problem current_time = current_time.AddSeconds(10); or refer to this link of my article http://www.c-sharpcorner.com/uploadfile/17e8f6/sending-automatic-mail-through-Asp-Net/
JataeditedPosted Feb 16, 2013, 4:27 AMEdited Feb 16, 2013, 4:36 AM
It is not sending mails.The problem is current_time is not matching with DateTime.Now.As if condition returns false its not entering inside the if condition.Plz check your if condition & then update your code.
naresh vaduguriPosted Jan 16, 2013, 10:34 AM
Thanks
sagar garagiPosted Oct 25, 2012, 4:27 AM
Thank You So Much.....
sagar garagiPosted Oct 25, 2012, 4:27 AM
Thank
Vishal GilbilePosted Jul 17, 2012, 6:17 AM
any error message you are getting make sure u rightly copied the code or else download the code.
Dang Dinh PhongPosted Jul 17, 2012, 5:16 AM
i don't know but it can't work. The my inbox is still empty. No everything error...
saurabh srivastavaPosted Jun 21, 2012, 5:25 AM
thanx for the help
Rajesh KumarPosted Sep 22, 2011, 12:24 AM
Hi What is Thread in ASP.NET.