473,569 Members | 2,691 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can a separate thread own a form control?

Basically what I have is a form with a graph on it which graphs data
that I'm reading from a USB device at 100 Hz (every 10ms). I have a
thread reading and parsing the data from the USB, but when it comes
time to draw that data on the graph the work is handled on the main UI
thread through a callback delegate since the form owns the graph
control. Is there a way I can have a separate thread own the graph
control and handle the drawing so that the rest of the UI is not
affected?

Thanks in advance,
Stu
Nov 18 '08 #1
3 4146
On Tue, 18 Nov 2008 09:09:55 -0800, <st*******@gmai l.comwrote:
Basically what I have is a form with a graph on it which graphs data
that I'm reading from a USB device at 100 Hz (every 10ms). I have a
thread reading and parsing the data from the USB, but when it comes
time to draw that data on the graph the work is handled on the main UI
thread through a callback delegate since the form owns the graph
control. Is there a way I can have a separate thread own the graph
control and handle the drawing so that the rest of the UI is not
affected?
What do you mean by "not affected"? In what way is "the rest of the UI"
being affected by your graphing that you believe would be addressed by
moving the graphing to a different thread?

The short answer is: yes, you can create your graphing control on a
different thread, and as long as you provide a message pump on that
thread, it should work fine.

But I fail to see the advantage in doing so. It would be helpful if you
could be more specific about what problem it is you perceive and which you
want to solve.

Pete
Nov 18 '08 #2
This is obviously a trimmed down version of the whole thing, but
should show you what I'm doing. ProcessUsbData is the thread which
reads in the data and calls the functions to update the graph and
textboxes. If I take out the UpdateO2Textbox (O2) and UpdateCO2Textbo x
(CO2) calls then the symptoms I'm seeing crop up. By the way, please
feel free to let me know if any of my code sucks and could be done in
a more efficient manner. For instance, if I'm supposed to be reading
from a USB once every 10 seconds is there a better way to do it than
doing Thread.Sleep(10 ) and then checking the inbound buffer? Thanks
again!
You don't need Thread.Sleep, because ReadLine should efficiently wait until
data is available.

bAbortRead should be volatile, because it changes from a different thread
than is reading it, with no synchronization .

You're making four cross-thread calls every time which is hurting
performance. And you should use MethodInvoker for maximum performance. Try
this:

volatile bool bAbortRead; // bool fields are initialized to false
by the compiler
private void ProcessUsbData( )
{
string[] data;
DateTime startTime = DateTime.Now;

while(!bAbortRe ad)
{
data = device.ReadLine ().Split(new char[]{','});

decimal ts = (DateTime.Now - startTime).Tota lSeconds;

decimal O2 = 0;
if(data.Length O2INDEX)
decimal.TryPars e(data[O2INDEX], out O2);

decimal CO2 = 0;
if(data.Length CO2INDEX)
decimal.TryPars e(data[CO2INDEX], out CO2);

MethodInvoker updateGUI = delegate {
if(O2 0 && O2 < 100)
{
AddDataPoint("O 2", ts, O2);
UpdateO2Textbox (O2);
}
if(CO2 0 && CO2 < 100)
{
AddDataPoint("C O2", ts, CO2);
UpdateCO2Textbo x(CO2);
}
};

if (InvokeRequired )
Invoke(updateGU I);
else
updateGUI();
}
}

>
public partial class frmSampleForm : Form
{
private bool bAbortRead;

Thread BufferReader;
delegate void AddDataPointCal lback(string series, decimal x,
decimal y);
delegate void UpdateO2Textbox Callback(decima l pValue);
delegate void UpdateCO2Textbo xCallback(decim al pValue);

public frmTesting_Veri fySetup(ref cExercise_Test pTest)
{
InitializeCompo nent();

ReadUSB();
}

private void ReadUSB()
{
// Start the thread which reads the inbound buffer
bAbortRead = false;
BufferReader = new Thread(new ThreadStart(Pro cessUsbData));
BufferReader.St art();
}

private void ProcessUsbData( )
{
string[] data;
decimal O2;
decimal CO2;
TimeSpan ts;
DateTime startTime = DateTime.Now;

while(!bAbortRe ad)
{
data = device.ReadLine ().Split(new char[]{','});

if(data.Length O2INDEX)
decimal.TryPars e(data[O2INDEX], out O2);
else
O2 = 0;

if(data.Length CO2INDEX)
decimal.TryPars e(data[CO2INDEX], out CO2);
else
CO2 = 0;

ts = DateTime.Now - startTime;
if(O2 0 && O2 < 100)
{
AddDataPoint("O 2", (decimal)(ts.To talSeconds),
O2);
UpdateO2Textbox (O2);
}
if(CO2 0 && CO2 < 100)
{
AddDataPoint("C O2", (decimal)(ts.To talSeconds),
CO2);
UpdateCO2Textbo x(CO2);
}

Thread.Sleep(10 );
}
}

private void AddDataPoint(st ring series, decimal x, decimal y)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if(chart1.Invok eRequired)
{
AddDataPointCal lback d = new AddDataPointCal lback
(AddDataPoint);
Invoke(d, new object[] { series, x, y });
}
else
{
chart1.Series[series].Points.AddXY(x , y);
chart1.Invalida te();
}
}

private void UpdateO2Textbox (decimal pValue)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if(txtO2.Invoke Required)
{
UpdateO2Textbox Callback d = new
UpdateO2Textbox Callback (UpdateO2Textbo x);
Invoke(d, new object[] { pValue });
}
else
{
txtO2.Text = pValue.ToString ("0.00");
}
}

private void UpdateCO2Textbo x(decimal pValue)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if(txtCO2.Invok eRequired)
{
UpdateCO2Textbo xCallback d = new
UpdateCO2Textbo xCallback(Updat eCO2Textbox);
Invoke(d, new object[] { pValue });
}
else
{
txtCO2.Text = pValue.ToString ("0.00");
}
}

}

Nov 19 '08 #3
On Tue, 18 Nov 2008 09:09:55 -0800 (PST), st*******@gmail .com wrote:
>Basically what I have is a form with a graph on it which graphs data
that I'm reading from a USB device at 100 Hz (every 10ms). I have a
thread reading and parsing the data from the USB, but when it comes
time to draw that data on the graph the work is handled on the main UI
thread through a callback delegate since the form owns the graph
control. Is there a way I can have a separate thread own the graph
control and handle the drawing so that the rest of the UI is not
affected?
Having followed the thread these thoughts come to mind. The issue
seems to be the side effects of trying to maintain the data display in
real-time. I recently ran into a similar issue writing a CAT
controller/monitor for a device with minimal documentation.
http://www.subdevo.com/FT897DCAT/

The device has thirteen buttons, seven rotary controls (three
concentric plus one), six LEDs and a ~2x3 inch LCD screen. All the
controls are multifunction. One of the things the LCD display can do
is act as a spectrum scope. This gives an idea of how much and the
kind of information the UI might be expected to display.

Each request/response pair exchanged describes part of the current or
desired state of the device. The state information is sent to the
device using five byte requests. Depending upon the request the
response may be zero to five bytes with a RTT of up to ~5 ms. Multiple
requests are needed to fully describe the device's state. At any time
the polling may be interrupted to send a request to the device to
change state.

Trying to update the numerous UI controls in real-time resulted in a
sluggish UI. My solution was to create an type which represents the
device's state to the UI. It is a composite object that essentially is
a middle tier between the device and UI. A worker thread (the
controller thread) runs a loop that manages various custom thread
objects. The callbacks go to the worker thread not the UI thread. Each
polled response partially updates the state.

This scheme lets the BL/TL/device wrappers to be packaged UI-free. A
timer in the UI fires periodically to update numerous UI controls with
data read from properties the clean, simple interface the state object
presents to the UI.. Changes to the device state are made from the UI
by changing state object's properties.

regards
A.G.



Nov 20 '08 #4

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

Similar topics

2
5850
by: Javier Bertran | last post by:
Hi all, I have an ActiveX control developed in Visual C++ 6.0 that I want to use in a C# project. I want the ActiveX code to run on a separate thread, but can't seem to get it to work. If for example my ActiveX member has an infinite loop, the .NET app gives all processing to the ActiveX and never returns, not even to redraw the window. Here...
28
4307
by: kfrost | last post by:
I know this is probably simple but I have a C# form and the class for the form is called sbaSynch. I have a textbox name txtServerName. I'm creating a class to manipulate XML functions so I added a class to project and it's named XmlApi(). In the XmlAPI() class I have simple code as following XmlAPI() { string str = "Some Text";
3
1874
by: JohnnyGr | last post by:
I have heard theres a new way to start threads with parameters in framework 2.0, does anyone know how to do that? this is what i need to do... Start a thread that executes some stuff, in this case it does gets all files from a directory. then i need to update the GUI with information from the thread... the thread should be started with...
5
2534
by: RWF | last post by:
I have a form, and from the form when a user clicks a button, it instantiates control that will be doing a lot of logic. I am trying to use System.Threading.ThreadPool.QueueUserWorkItem to spawn a background thread off the pool. I stepped through the logic, and everything seems to go through fine when the control is initialized, and my main...
0
1372
by: Jaret Brower | last post by:
I'm trying to parse html that resides locally by using the HtmlDocument class and unfortunately you can only get an instance of an HtmlDocument through the WebBrowser control. Some of the html files I want to parse are quite large so I want to get the HtmlDocument in a separate thread. But for some reason, whenever I move the code to...
8
5341
by: =?Utf-8?B?R3JlZyBMYXJzZW4=?= | last post by:
I'm trying to figure out how to modify a panel (panel1) from a backgroundworker thread. But can't get the panel to show the new controls added by the backgroundwork task. Here is my code. In this code there is a panel panel1, that I populate with a lable in the foreground. Then when I click on "button1" a backgroundworker thread in async...
9
18007
by: RvGrah | last post by:
I'm completely new to using background threading, though I have downloaded and run through several samples and understood how they worked. My question is: I have an app whose primary form will almost always lead to the user opening a certain child window that's fairly resource intensive to load. Is it possible to load this form in a...
9
5049
by: koschwitz | last post by:
Hi, I hope you guys can help me make this simple application work. I'm trying to create a form displaying 3 circles, which independently change colors 3 times after a random time period has passed. I'm struggling with making the delegate/invoke thing work, as I know GUI objects aren't thread-safe. I don't quite understand the concept I'm...
10
5042
by: Paul E Collins | last post by:
I want to fill an ImageList with bitmaps for a ListView from another thread, because it's a time-consuming process. I expect the ListViewItems' images to "load" one by one, as in a Web browser. I wrote the following code, but the form freezes up while CreateTileBitmaps is running, just as if I'd done it on the main thread. How can I add...
0
7612
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7924
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8122
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6284
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...
1
5513
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...
0
5219
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...
0
3640
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2113
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
1
1213
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.