How To Start A New Thread To Query A Database While Web Application Continues Running

Feb 11, 2011

I want to start a new thread to query a database while my web application continues running. I was under the impression that by using threads I can run the querying process independently while the normal web application page cycle carries on, but I could be wrong.

public class DbAsyncQuery
{
Dictionary<string, object> serviceResults = new Dictionary<string, object>();
public void UpdateBillingDB()
{
QueryAllServices();
foreach (KeyValuePair<string, object> p in serviceResults)
{
IEnumerable results = (IEnumerable)p.Value;
IEnumerable<object> sessions = results.Cast<object>();
DbUtil.MakeBillingDBEntry(sessions, p.Key);
}
}
public static string[] servicesToQuery = new string[] // Must go in config file ultimately
{
"xxx.x.xxx.xx"
};
public delegate void Worker();
private Thread worker;
public void InitializeThread(Worker wrk)
{
worker = new Thread(new ThreadStart(wrk));
worker.Start();
}
public void InitializeQuery()
{
Worker worker = QueryAllServices;
InitializeThread(worker);
}
private void QueryAllServices()
{
Dictionary<string, DateTime> lastEntries = DbUtil.GetLastEntries();
foreach (string ip in servicesToQuery)
{
string fullServicePath =
"http://" + ip + ":800/MyWebService.asmx";
//object[] lastEntry = new object[] { lastEntries[ip] };
object[] lastEntry = new object[] { new DateTime(2011, 1, 1, 0, 0, 0) };
object obj = WebServiceHandler.CallWebService
(fullServicePath, "MyWebService", "GetBillingDBEntries", lastEntry);
serviceResults.Add(ip, obj);
}
}
}

It seems to basically stall and wait to finish the query before loading the page (which can be thousands of rows, so it takes awhile). I put this in the following section of Global.asax:

protected void Application_Start(object sender, EventArgs e)
{
DbAsyncQuery query = new DbAsyncQuery();
query.UpdateBillingDB();
}

This is one of my first web pages, and I'm new to threading. I understand there is a difference between creating your own thread and using the ThreadPool. In this method, I am using my own thread, I think. Not sure if that's the best way. The querying process can be completely independent, and its only going to occur on scheduled intervals (every 8 hours or so). The user doesn't need to have up to the minute data, so it can take awhile. I just don't want the site to wait for it to finish, if that's possible.

View 1 Replies


Similar Messages:

C# - Continuously Running Thread In Web Application?

Mar 31, 2011

i want a continously running thread in my web application for sending mail to admin if the logged complaint of the user in not solved by technician within 24 hours.

i am able to send mail to administrator

i just want a watch on database for unsolved issues with timespan of more than 24 hours and inform to administrator about the same

View 3 Replies

Create A 'thread' To Execute A Function On Page Load / Application Start?

Jan 10, 2011

I need to call a function everytime a visitor visits one of my website's page. But I do not want the execution of the function to interfere with the interface between the user and the website i.e. different thread. What is the best way to do that on ASP.Net?

View 3 Replies

Web Forms :: Start Two Asynchronous Database Access Calls That Are Executed Onto The Separate Thread?

Sep 2, 2010

i have the code for asynchronous call to the database. i execute the sql command into the begin method that will executed onto the separate thread. now i want to execute the another database call asynchronously so that this also execute onto the separate thread. code for one database cal is here....

private SqlConnection con, con1;
private SqlCommand cmd, cmd1;
private SqlDataReader dr, dr1;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddOnPreRenderCompleteAsync(new BeginEventHandler(Begin),
new EndEventHandler(End)
);
}
}
/////////////BEGIN METHOD
IAsyncResult Begin(object sender, EventArgs e,AsyncCallback cb, object state)
{
string connect = "Data Source=.\SQLEXPRESS;Asynchronous Processing=true;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True";
con = new SqlConnection(connect);
con.Open();
cmd = new SqlCommand("SELECT FirstName,LastName,Age,Company,Profile FROM Person",con);
return cmd.BeginExecuteReader(cb, state);
}
//////END METHOD
void End(IAsyncResult ar)
{
dr = cmd.EndExecuteReader(ar);
Label2.Text = System.Threading.Thread.CurrentThread.GetHashCode().ToString();
GridView1.DataSource = dr;
GridView1.DataBind();
}

View 1 Replies

C# - Application Running Under A Less Privileged Account Start A Process Executing Another Application Under An Administrative Account?

Mar 9, 2011

I am logged in as the administrator when I installed an application named pdflatex.exe on my server. This application works as a converter from LaTeX input file to Pdf file. I host an Asp.net MVC 3 application running under an Application Pool Identity with Load User Profile = True. The Asp.net MVC 3 code contains a code that executes pdflatex.exe using System.Diagnostic.Process instance as follows:

Process p = new Process();
p.EnableRaisingEvents = true;
p.Exited += new EventHandler(p_Exited);
p.StartInfo.Arguments = "-interaction=nonstopmode " + inputpath;
p.StartInfo.WorkingDirectory = @"c:mydomain.comworking";
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "pdflatex.exe";
p.Start();
p.WaitForExit();

From the scenario above, the web application runs under a restricted acount but it executes an external application under a default account that I don't know. Can an application running under a less privileged account start a process executing another application under an administrative account?

View 2 Replies

Web Forms :: Timeout Error Continues On Long - Running Web App Supposedly Already Configured To Accommodate Long

Jun 16, 2010

I've developed a web application to accept video file uploads and then pass them to a backend service on an external server. The application runs without error on the visual studio debugging webserver, but once on a production iis 6 or 7 server, yields a timeout error at about a consistent amount of time into handling a large upload. Specifically, it errors in the middle of transferring the video file to the external server, once the application has successfully received it from the client. I'm aware of several timeouts to be configured related to the problem, and have done so. The application's web config has been tested with one or both of the following settings

<system.web>
<httpRuntime executionTimeout="9999999" maxRequestLength="2048000" />
</system.web>
and
<configuration>
<location path="default.aspx"> (the page at issue that's timing out)
<system.web>
<httpRuntime executionTimeout="9999999" maxRequestLength="2048000" />
</system.web>
</location>
</configuration>

And within the initialization of the webrequest made to the external server to send the video received from the client browser:

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = System.Threading.Timeout.Infinite;

So with the execution time limits on both the webform as a whole and the connection made to the external server, I'm at a loss for what timeout is left unconfigured, or how to determine such, when I continue to get the following error: Unexpected error executing Brightcove Upload:...........................

View 3 Replies

Data Controls :: ProgressBar Thread With Database In Windows Forms Application

May 22, 2013

How to use progressBar with thread in windowsApplication..

I have a for loop in c# layer when loop start progressBar with start and  when loop finish progressBar is full ???

View 1 Replies

Web Forms :: How To Start / Suspend / Resume Thread

Jul 16, 2010

check this code about threading ..

i am getting different o/p every time. just i want to start the thread ,suspend that thread and resume that thread .

namespace ThreadTest
{
class Program
{
static void Main(string[] args)
{
Thread th = new Thread(new ThreadStart(new Program().Call));
th.Start();
Console.WriteLine("STARTED");
th.Suspend();
Console.WriteLine("SUSPENDED");
th.Resume();
Console.WriteLine("RESUMED");
Console.ReadLine();
}
public void Call()
{
for (int i = 1; i < 200; i++)
{
Console.WriteLine(i.ToString());
}
}
}

View 5 Replies

Web Forms :: At Initial Page Load Start A Thread

Jun 17, 2010

I have an application that initially display 4 grid views at page load. This process takes 50-60 seconds and I would like to change the process to display the web page, show message like "Data being loaded, please wait..." and then spin off a thread that fills the various grid view. When this is done I would programatically like to do a post back to show the result. Not sure if this is possible? I tried something like this:

[Code]....

View 1 Replies

Is It Acceptable To Cache An Instance Of The Database Connection On Application Start

Jan 5, 2010

Is it acceptable to cache an instance of the database connection on application start?

Looking at the MSDN documentation on thread safety, I quote:

Any public static [...] members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Given that, is it acceptable/safe for code such as this example below:

[code]...

View 1 Replies

How To Optimize The Performance Of A Thread Running In Background

Feb 4, 2011

In my website, I am using thread to perform a repetitive process in background. Now the process takes around 30 to 45 seconds to update the database.

Basically the function performs the following:

1) Download the CSV from a website.

2) Parse the CSV and update the database tables.

I want to optimize the performance and decrease the time it takes to 15 seconds.

How can I do this?

EDIT:

Here is the Code:

[code]....

View 1 Replies

ThreadPool Thread Running As User =ASPNET

Nov 24, 2010

I have a web service that uses ThreadPool to delegate a task to a thread but it runs on ASPNET (System.Environment.UserName) while the main thread runs as windows account. How can I make this thread run with same windows account. Note that I have impersonate=true in web.config. This is causing problems accessing database.

View 1 Replies

SQL Server :: How To Connect An Application Running In Local IIS To Database

Sep 28, 2010

how to connect an asp.net application running in local IIS to a database residing in a remote web server ?

View 2 Replies

Getting Website's URL Without HttpContext.Current (running In Background Thread)?

Aug 3, 2010

Bit of a long shot, but is there a way in ASP.NET to dynamically get the website's URL [URL] when there is no HttpContext.Current available.

There is no HttpContext because the code is running in a background thread* (but under the ASP.NET AppDomain). I have a background process that sends emails out every evening, and needs to include the Web address, but I don't want to hard code it because of deployments and testing (it changes from [URL] to[URL] and then to [URL] for the live site).

View 2 Replies

C# - Registering Routes On Session Start Not Application Start?

Jan 26, 2011

I am trying to register the route collection in .net based on each session. The code I have works fine, you goto website/username and it loads the correct sub pages, but you have to restart the application to goto website/username2 to load those sub pages. But when the application is restarted the second one works, but then not the first one. Is there some way to create a different route collection per session not per application using system.web.routing.

View 3 Replies

Does The Continuously Running Thread In Background Impact The Website's Performance

Feb 3, 2011

In my website I am using thread to perform the function which downloads the CSV from a website and parses the data into the database.

Now if I am not able to stop the thread then what could be the impact on the performance?

Also If I unknowingly start another thread then would it impact my website's performance?

View 3 Replies

Cross-thread Operation Not Valid: Accessed From A Thread Other Than The Thread It Was Created On

Apr 2, 2010

I want to remove checked items from checklistbox (winform control) in class file method which i am calling asynchronously using deletegate. but it showing me this error message:-

Cross-thread operation not valid: Control 'checkedListBox1' accessed from a thread other than the thread it was created on.

i have tried invoke required but again got the same error. Sample code is below:

[code]....

View 1 Replies

C# - Start Timer On Web Application Start

Jun 8, 2010

I would like to start a System.Threading.Timer in my application when it launches (maybe deploy is the correct word). I have seen that you can use Application_Start() but this is only fired once the first request comes to the application. I need the timer to start as soon as the application is running so that it can check for work to process even if a user is not interacting with the site. How can I get the application to start the timer once it is up and running?

View 4 Replies

Force A New Start Of "Cassini" When Start Debugging A New Instance Of Web Application?

Feb 25, 2011

In our ASP.NET application we perform some initializations upon the Application Start event.When the application is started in visual Studio 2010 with 'Debug->Start new instance' the ASP.NET Development server does not start new, and my Application's Start event is not fired.My workaround is to manually stop the development server - is there a setting to force this automatically?

View 1 Replies

Start Batch Job From IIS / Start Exe File With System.Diagnostics.Process.Start With Another Account Is Disabled?

Oct 28, 2010

What is the right approach when users (authenticated domain admins) should be able to start batch jobs (usually exe files) from an IIS (7.x) aspx (c#) page? This is an intranet site. The batch jobs have to run on the web server as Domain Admins. The website pool is executed by network service or some similar restricted account in AD.

Approaches I can think of (and their disadvantages):
1. Start exe file with System.Diagnostics.Process.Start with another account. This feature is disabled in IIS 7.x, how do I allow it?

2. Create a sheduled task and call scheduled task-api. This unmanaged dll is giving VS compiler warnings because it's unsafe to call from managed code.

3. I suppose there's a better approach, because the previous suggestions doesn't appear safe or robust.

View 2 Replies

Visual Studio :: Application Has Failed To Start Because The Application Configuaration Is Incorrect?

Apr 8, 2010

on desktop start has disappeared, getting above issue on double clicking/running any application.have VS2005 installed with sp1 and all other relevant updates as per MS..., i read some forums which states because of VC++ the system files may be currupted....have not installed VC++can anyone guide me the issue here and its solution...

View 3 Replies

How To Handle .NET Application Error That Occurs On Application Start And Transfer

Mar 9, 2010

I know that ASP.NET MVC has error filter attribute to handle specified error type. However, this feature cannot catch any error that occurs when application start. Therefore, I need to add some code to "Application_Error" method for handling this error like the following code.

public void Application_Error(object sender, EventArgs e)
{// At this point we have information about the error
var ctx = HttpContext.Current;
var exception = ctx.Server.GetLastError();
[code]...

View 1 Replies

Application Domain Vs Thread - Relationship?

Mar 29, 2010

Can someone explain me what is is the relationship between App Domain and thread? msdn says "threads are free to cross application domain boundaries; a new thread is not created for each application domain." suppose there is one thread t inside Appdomain a1 .there is an another App domain a2 .thread t can cross to a2 from a1 means it can access a2 memory area If thread can cross the app domain boundaries share the memory space then how application domain isolation is still there?

View 5 Replies

Multithreading - Want To Create A Thread In A Mvc Application?

Nov 5, 2010

I want to create a thread in a asp.net mvc application. What will happen?

A) Thread will die when request ends and the response is sent.

B) Thread will continue to run and response will be sent when thread terminates.

C) Thread will run without blocking the response and die when it have completed it's task

View 1 Replies

Web Forms :: Query DataTable To Get Records Between Start And End Dates

Apr 5, 2012

I have to filter the records from the data table based on the date.

I am having a column in data table called "cStartDate".

I will enter the begin and end date. I have to find out whethere the "cStartDate" is within the begin and end date i entered.

I am going to implement the filter logic in data table with out affecting the data base.

I need a Filter string for this.

View 1 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved