Home > front end >  Enable and disable button while running thread in asp.net
Enable and disable button while running thread in asp.net

Time:12-27

In the button click in web application asp.net, i have created a thread.Inside the thread, I am trying to disable the button and do some background jobs. Background jobs working perfectly but button disabling is not working. MY CODE IS:

private void generteBtn_Click(object sender, EventArgs e)
{
   new Thread (() =>
    {
       btn.enabled = false;
       // thread work start here;
       //emailing
    }.start();
     
}

My question is how can I disable buttons while the threads are working and re enable generteBtn_Click after the threads finished.

CodePudding user response:

because the thread that you created here is not the UI thread and to access any element in the UI thread you can use:

Application.Current.Dispatcher.Invoke(() =>
{
    btn.enabled = false;
});

and for more details you can check these links:

1- How do I get the UI thread's Dispatcher?

2- Dispatcher.Dispatch on the UI thread

CodePudding user response:

Hide/show the buttion BEFORE you start the next process/thread.

eg:

       btn.enabled = false;
      new Thread (() =>
      {
      // thread work start here;
      //emailing
      }.start();

That way, the button is disabled, process starts, as always then a whole new fresh copy of the web page is then sent back to the client side.

If you need to update that page? Then you have really only 2 practial choices.

You can start a timer on the page - call a ajax routine, and it will have to check say some session() value that the process sets = "done".

The other way would be to introduce signalR into your applcation.

https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/introduction-to-signalr#:~:text=What is SignalR? ASP.NET SignalR is a library,process of adding real-time web functionality to applications.

I have a number of processing routines. I start the process, and the I start a timeer on the page. It re-freshens a update panel every 1 second until such time the session("MyProcessDone") = true, and then I stop the timer at that point (and of course update the spinner/animated gif). So, you can start a timer on the web page - and check some session() value, or as noted, introduce signalR into your applicaton.

  • Related