473,765 Members | 2,047 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using the BackgroundWorke r and a SqlDataReader

Hi,

I've written a simple app which should just fetch some data from a
database and render the results into a ListView.

In order to not freeze the GUI, I'm using a BackgroundWorke r. The
arguments for the RunWorkerAsync are the Query to be executed and the
Connectionstrin g. As a result I hoped I could return a SqlDataReader.

The problem is, if I create the SqlDataReader within the
BackgroundWorke r Thread, I can't access it after the Thread has exitted.
If I would create it on the Form (thus within the Forms Thread) and pass
it as an argument to the Thread, I might end up with the risk of two
Threads accessing the same resource (a Forms Property in this case) and
that doesn't sound a nice thing to do.

How can I pass the resulting SqlDataReader from the Thread back to the form?

Any help is greatly appreceated and thanks in advance!

Matthias
Nov 16 '05 #1
2 7406
Matthias,

Can you show an example of how you are using the BackgroundWorke r class?
AFAIK, you shouldn't have an issue if you create a SqlDataReader and pass it
around (the OleDb provider I can understand, but not the SqlProvider).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Matthias S." <po*****@emvoid SPAMTRAP.de> wrote in message
news:uB******** ******@TK2MSFTN GP09.phx.gbl...
Hi,

I've written a simple app which should just fetch some data from a
database and render the results into a ListView.

In order to not freeze the GUI, I'm using a BackgroundWorke r. The
arguments for the RunWorkerAsync are the Query to be executed and the
Connectionstrin g. As a result I hoped I could return a SqlDataReader.

The problem is, if I create the SqlDataReader within the BackgroundWorke r
Thread, I can't access it after the Thread has exitted. If I would create
it on the Form (thus within the Forms Thread) and pass it as an argument
to the Thread, I might end up with the risk of two Threads accessing the
same resource (a Forms Property in this case) and that doesn't sound a
nice thing to do.

How can I pass the resulting SqlDataReader from the Thread back to the
form?

Any help is greatly appreceated and thanks in advance!

Matthias

Nov 16 '05 #2
Hi Nicholas,

I'm trying to copy/paste the most relevant parts. All ErrorHandling has
been removed. Basically, we need to know only the two EventSinks for the
following BackgroundWorke r events:

- DoWork
- RunWorkerComple ted
This is the EventSink for the DoWork event:

private void OnWorkerStart(o bject sender, DoWorkEventArgs args) {

// the DBWorkerArgs contain two public fields which are
// quite selfexplanatory : ConnectionStrin g and Query
DBWorkerArgs workerArgs = (DBWorkerArgs) args.Argument;

// open connection
SqlConnection con = new SqlConnection(w orkerArgs.Conne ctionString);

con.Open();

// run the query again, checks on the SqlConnection ommitted...
SqlCommand cmd = new SqlCommand(work erArgs.Query, con);
SqlDataReader reader = cmd.ExecuteRead er();

// to make the Results available in the
// BackgroundWorke r.RunWorkerComp leted event, we put them
// into the args.Result

args.Result = reader;

con.Close();

// done...
}

This is the EventSink for the RunWorkerComple ted event:

private void OnWorkerComplet ed(object sender,
RunWorkerComple tedEventArgs args) {

// typechecking omitted
SqlDataReader reader = (SqlDataReader) args.Result;

// _ResultList is a ListView Control on the Form
_ResultList.Ite ms.Clear();
_ResultList.Col umns.Clear();

// columns first
int nFieldCt = reader.FieldCou nt;

for (int i = 0; i < nFieldCt; i++) {
_ResultList.Col umns.Add(reader .GetName(i), 100);
}
}

Both methods are located withing Form1.

Thanks already for looking into my issue :)

Matthias

Nicholas Paldino [.NET/C# MVP] wrote:
Matthias,

Can you show an example of how you are using the BackgroundWorke r class?
AFAIK, you shouldn't have an issue if you create a SqlDataReader and pass it
around (the OleDb provider I can understand, but not the SqlProvider).

Nov 16 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
5889
by: Neil Guyette | last post by:
Hello, Everyone, I'm trying to find information on how to populate a combo box using a SqlDataReader. I want to be able to set the value of the combo's value property different then the combo's text property (what the user will see). Is this possible with a SqlDataReader? Thanks
3
9984
by: Pro1712 | last post by:
Hi, this may be a stupid question: How can I can call the DoWork-function of a BackgroundWorker synchronous? Or in other words: How can I extend the BackgroundWorker class with a function RunWorkerSync()?
11
7335
by: GVN | last post by:
Hi All, Can anyone guide me when asynchronous method calls will be benificial? Are there any disadvantages of using asynchronous calls? Thanks,
1
3232
by: Bob | last post by:
Hi, I am having trouble seeing how this bolts together. The UI starts a process which involves a long running database update. All Database activity is handled by a class called DT. DT has a progress event. So I added a bw to the form. The Dowork Calls a method which instantiates a DT and calls its Dataprocessing method.
5
11234
by: redear | last post by:
Is there a way to immediately terminate a BackgroundWorker thread? My problem is that the BackgroundWorker starts with a call to My.Computer.FileSystem.GetFiles that can run for a very long time if it is pointing to a directory tree with many files. If the user requests cancellation during this time, the main thread can call CancelAsync and can post a "Cancellation Pending" message to the user, but the BackgroundWorker cannot respond to...
5
5560
by: Michael M. | last post by:
I have the following code (listed at bottom of post) that pings a small range of IP address to see which ones are alive. To speed things up a little I am trying to use more than one thread, problem is instead of returning: 192.168.0.1 online
0
2480
by: Chris | last post by:
I would like to be able to pass the BackgroundWorker object and DoWork Event Args to a second function (third function?) and be able to still report the progress. I'm getting the following exception when trying to access BackgroundWorker.CancellationPending or e.Cancel An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll Additional information: Exception has been thrown by the target of...
2
1821
by: Peter Carlson | last post by:
I am testing backgroundWorker to update our installer with both messages and with a progress bar. I am finding however that the text never gets updated. Any ideas what I might be doing wrong? Code snipped for brevity. Peter private BackgroundWorker worker; private void Install_Click(object sender, EventArgs e) { worker = new BackgroundWorker();
0
1901
by: PeterSchwennesen | last post by:
Problems starting a Timer Programmatically within a BackgroundWorker. I am trying to start a Timer inside a Backgroundworker. I want to start the BackGroundWorker and then have a timer tick a calculation reppeting inside the BackGroundWorker. The Code below seems to work ok for sending back the informaton "DoWork - Enter" and "DoWork - Exit, but the Timer "Timer_Ping" is newer ticked and the line "Time - Tick" is newer send back. Why is my...
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9835
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8833
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7379
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5277
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3926
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.