armyjam
armyjam

Reputation: 11

[C#]Response.write is not working when use Thread

In main method I use this thread to call the send email function.

    protected void updateBtn_Click(object sender, EventArgs e)
    {                
    Thread email = new Thread(delegate ()
            {
                sendmail(//send some string);
            });
            email.IsBackground = true;
            email.Start();
    }

There some Response.Write in sendmail() method and when I'm trying to debug it's show error

System.Web.HttpException: 'Response is not available in this context.'

This is sendmail()

private void sendmail(//string input)
{
       //do something about smtp
       Response.Write("Test message");
}

Upvotes: 0

Views: 287

Answers (2)

Purvesh Patel
Purvesh Patel

Reputation: 86

I have checked your code it's working perfectly

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //GetData();

                CheckThread();
            }
        }

        private void CheckThread()
        {
            Thread email = new Thread(delegate ()
            {
                sendmail();
            });
            email.IsBackground = true;
            email.Start();
        }

        private void sendmail()
        {
            Response.Write("Call this function!");
        }

enter image description here

Upvotes: 0

Eric J.
Eric J.

Reputation: 150148

The Response object is associated with the button event handler and not available in the new thread you start.

The event handler exits shortly after you start the new thread. Anything written to Response must be done before that handler returns.

Upvotes: 1

Related Questions