Interacting with UI threads in Java/J2ME - c#

I'm writing a J2ME application. One of the pieces is something that polls the contents of a directory periodically, and, if there are any new things, paints them on the screen. I've done this by having the UI form launch a polling thread with a pointer back to itself, and when the polling thread finds something it calls back to the form and calls a syncrhonized method to update it's display. This seems to work fine.
The question I have is this. In C#/.NET I know it is not nice to have non-UI threads updating the UI, and the correct way to handle this is to delegate it up to the UI thread.
E.g. the following:
public void DoSomeUIThing()
{
if (this.uiComponent.InvokeRequired)
{
this.uiComponent.Invoke(someDelegateThatCallsBackToThis);
}
else
{
this.uiComponent.Text = "This is the update I want to happen";
}
}
Is there a J2ME equivalent for how to manage this process? How about Java? Or does Java/J2ME just play nicer in regard to this? If not, how is this done?
[EDIT] It appears that Swing supports what I'm asking about via the SwingUtilities.invokeLater() and invokeAndWait() methods. Is there an equivalent framework for J2ME?

Regarding Java, what you are describing looks like a SwingWorker (worker thread).
When a Swing program needs to execute a long-running task, it usually uses one of the worker threads, also known as the background threads.
A Swing program includes the following kinds of threads:
Initial threads, the threads that execute initial application code.
The event dispatch thread, where all event-handling code is executed. Most code that interacts with the Swing framework must also execute on this thread.
Worker threads, also known as background threads, where time-consuming background tasks are executed.
Single-thread rule:
Once a Swing component has been realized, all code that might affect or depend on the state of that component should be executed in the event-dispatching thread.
When used in a J2EE context, you need to be careful when you are referencing a SwingWorker from an EJB.
Regarding J2ME, it depends if you are developing your application as a standard MIDlet that will run on any MIDP-enabled device, or for instance as a RIMlet, a CLDC-based application that uses BlackBerry-specific APIs and therefore will run only on BlackBerry devices.
Because unlike MIDP's UI classes, RIM's are similar to Swing in the sense that UI operations occur on the event thread, which is not thread-safe as in MIDP. To run code on the event thread, an application must obtain a lock on the event object, or use invokeLater() or invokeAndWait() – extra work for the developer, but sophistication comes with a price tag.
But for LCDUI, you can access a form from multiple threads.

There are many profiles of Java ME. If you mean MIDP then Display.runSerially is what you want.
For AWT (Swing) you would use EventQueue.invokeLater (SwingUtilities.invokeLater is only necessary due to Java 1.1 not having the EventQueue method - 1.2 is about to celebrate its tenth birthday). For the Common DOM API, use DOMService.invokeLater.
No matter what claims a GUI API may make about thread-safety they are probably wrong (some of the claims of Swing are removed in JDK7 because they are not implementable). In any case, application code unlikely to be thread-safe.

For j2me apps you probably want to keep it simple. The main thing is to touch UI components only in the event thread. The direct way of doing this is to use invokeLater or invokeAndWait. Depending on your libraries you won't have access to anything more than that. In general if these aren't provided in your platform it probably equates to there being no thread support and not being an issue. For example the blackberry does support it.

If you develop under SWT this is accomplished by means of asyncExec() method of Display object. You pass an object implementing Runnable so the UI thread executes the changes done in other thread.
This is an example borrowed from here
public void itemRemoved(final ModelEvent me)
{
final TableViewer tableViewer = this.viewer;
if (tableViewer != null)
{
display.asyncExec(new Runnable()
{
public void run()
{
tableViewer.remove(me.getItem());
}
}
}
}

I can attest that the MIDP UI toolkit is indeed thread-safe, as I have large MIDlets with complex GUI running on millions of phones made by almost every manufacturer, and I have never seen a problem in that regard.

Related

Unintentional multithreading in form application

I recently created a form application through the Windows Form Application template in Visual Studio. I think the program was automatically created with multiple threads, putting the UI on one thread and whatever else on the other thread. I didn't put any code in the application to use multithreading.
Regardless I ran into and fixed the error described here. An error was thrown because I accessed a UI object from within the code block below. The issue being that the code was being ran from a different thread than the UI's thread.
What I want to know is the program actually using multiple threads? and if so how do I prevent that from happening. If not, what is happening here?
For reference, the code where I ran into this issue was in the same class that I initialize the form with. The line where I ran into the issue was on the last line in the CheckUp function (which has been altered to allow different thread access).
Note: The code is structured to be moved to a console app, so the timer method and some other stuff is less kosher
public partial class Form : System.Windows.Forms.Form
{
public Form() {
InitializeComponent();
System.Timers.Timer actionTimer = new System.Timers.Timer(1000);
actionTimer.Elapsed += actionTimerTick;
actionTimer.AutoReset = true;
actionTimer.Enabled = true;
}
private void actionTimerTick(object sender, EventArgs e) {
CheckUp();
}
public void CheckUp() {
bool onlineStatus = GetOnlineStatus();
string status = (onlineStatus) ? "Online" : "Offline";
statusOutputLabel.Invoke((Action)(() => statusOutputLabel.Text = status ));
}
private static bool GetOnlineStatus() {
/*unrelated*/
}
}
What I want to know is how to do manipulate the program to run everything on a single thread so that I do not have to worry about adding the extra code to manipulate UI objects,
Easy. Just don't add any explicit create-thread code in your Windows Forms app.
I recently created a form application through the Windows Form Application template in Visual Studio. The program was automatically created with multiple threads, putting the UI on one thread and whatever else on the other thread (I think).
Applications created by the Windows Forms Application template are inherently single-threaded by default so not sure why you think you have additional threads.
If you did create additional worker threads with respect to that other post, then you should use Control.BeginInvoke rather than Control.Invoke since the later can lead to potential thread dead-lock.
Additional
GUI toolkits like WinForms are potentially always single-threaded. For a jolly-good read as to why check out this article.
KGH:
The problem of input event processing is that it tends to run in the opposite direction to most GUI activity. In general, GUI operations start at the top of a stack of library abstractions and go "down". I am operating on an abstract idea in my application that is expressed by some GUI objects, so I start off in my application and call into high-level GUI abstractions, that call into lower level GUI abstractions, that call into the ugly guts of the toolkit, and thence into the OS. In contrast, input events start of at the OS layer and are progressively dispatched "up" the abstraction layers, until they arrive in my application code.
Now, since we are using abstractions, we will naturally be doing locking separately within each abstraction. And unfortunately we have the classic lock ordering nightmare: we have two different kinds of activities going on that want to acquire locks in opposite orders. So deadlock is almost inevitable. Golly, tell me more...
And that's why, like Java AWT, WinForms is also single-threaded.
See also
kgh, "Multithreaded toolkits: A failed dream? Blog", https://community.oracle.com/blogs/kgh/2004/10/19/multithreaded-toolkits-failed-dream, retrieved 2016/7/27
You are using System.Timer. https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx
For winforms apps you are better off using the one for winforms...
https://msdn.microsoft.com/en-us/library/system.windows.forms.timer(v=vs.110).aspx
It is designed to support single threaded UIs. :-
A Timer is used to raise an event at user-defined intervals. This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.

C# - When to Make Thread-Safe Calls

I have a large project that I'm working on in C#, a language I'm fairly new to. The project heavily relies on a GUI and there is a lot of data that is displayed. Recently, we've been getting cross-threading errors in places that they never were before. These errors where they occurred were easily solved:
if (logListView.InvokeRequired)
{
logListView.BeginInvoke(new MethodInvoker(
() => logListView.Items[logListView.Items.Count - 1].EnsureVisible()));
}
else
{
logListView.Items[logListView.Items.Count - 1].EnsureVisible();
}
My question however, is this: Does that method need to be applied EVERY TIME I access a Windows Form object? Are there special cases? I'm not using multi-threading, so to the best of my knowledge where these errors occur are out of my control. E.g. I can't control which piece of code is executed by which thread: C# is doing all of that on it's own (something I don't really understand about the language). Implementing an if statement for each line that modifies the GUI seems exceptionally obnoxious.
You only need that code if you access winform components from outside the UI thread (ie. from any thread you have spawned). There are some components in the core library that spawn threads, for example the FileSystemWatcher. Winforms doesn't just spawn threads on its own, it only has the UI thread. Any cross-thread issues occur because of code you wrote or libraries you use.
You only need to invoke the code when the code is not running in the GUI thread.
I can't control which piece of code is executed by which thread
Yes, you can. There is nothing unpredictable about which code runs in the GUI thread, you just have to find out what the rules are.
The only code to run out of the GUI thread in your code would be methods that runs as an asynchronous callback, for example a timer or an asynchronous web request. (The System.Windows.Forms.Timer runs the Tick event in the GUI thread though.)
(There are other ways of running code in another thread, but then you would be aware of using multi-threading.)

Implementing Thread in Java from a C# background

I'm trying to implement multithreading in my Java GUI application to free up the interface when a couple of intensive methods are run. I'm primarily from a C# development background and have used Threads in that environment a couple of times, not having much difficulty of it all really.
Roughly:
C#
Create a Thread object
Assign it a method to start from
Start thread
Now onto the Java app itself, it's a GUI application that has a few buttons that perform differrent actions, the application plays MIDI notes using the MIDI API and I have functions such as play, stop and adding individual notes. (A key thing to note is that I do not play MIDI files but manually create the notes/messages, playing them through a track).
There are three particular operations I want to run in their own thread
Play stored MIDI notes
Display a list of instruments via a text box
Generate 100 random notes
I have a class called MIDIControl that contains all of the functionality necessary such as the actual operations to play,stop and generate the messages I need. There is an instance of this object created in the FooView.Java class for the GUI form itself, this means for example:
Press "Generate"
Event handler performs the "GenerateNotes" method in the FooView.Java class
This method then performs the "Generate" method in the MIDIControl instance
I've looked at implementing threads through Java and from what I've seen it's done in a different manner to the C# method, can anybody explain to me how I could implement threads in my situation?
I can provide code samples if necessary, thanks for your time.
Java threads are created the same way as C# threads, except that you pass the thread a Runnable implementation instead of a delegate. (Because Java doesn't support delegates)
Java Concurrency in Practice is your guide. Pls also have a look at SwingWorker. Remember that all UI related changes (either component model or its properties) should always be done on Event Dispatch Thread.
Background tasks in Java GUI applications are often done using the SwingWorker class, which is designed specifically for that purpose.
You'll need to distinguish between tasks that update the GUI, and tasks that do not.
If your task needs to update GUI elements, such as your task (2), you'll need to sub-class SwingWorker. The processing code (calls to your exising library) go in your override of doInBackground(), sending out any data through publish(). Then, your SwingWorker process() override can interact with your Swing components.
The reason: Swing is not thread-safe, so it will potentially break if accessed from threads other than the Event Dispatch Thread (EDT). process() will run in the EDT.
For tasks that don't update the GUI, create a new class which implements Runnable and insert the appropriate MIDI library code call in the run() method. You may then pass this as a target to a new thread as in new Thread(myRunnable).start().
As others have said it's the SwingWorker class you're after, this will enable a swing component to fire off a task in another thread and be notified of its completion and progress in a thread safe manner. You can't just spout off random threads using the raw thread runnable objects and then expect to interact with swing through those threads; swing is not thread safe by design so by doing things this way you'll almost certainly introduce subtle threading bugs into your code.
Depending on what version of Java you're using you can either download the SwingWorker separately or use the one built into the API.
If you're using Java 6 (or above) then swing worker is in the core API here.
If you're using Java 5 then the Java 6 version has been backported here.
If you're using an earlier version then you'll have to add sun's original version in which is here.

C# WinForms application: stop / interrupting a Windows Forms application

Environment: .net 3.5 WinForms application
I am looking for some ideas how to stop / interrupting a Windows Form application, e.g. when “something” takes too long.
A typical scenario is reading large amount of data from a backend system and the user shall be able to press some key immediately stopping the loading.
Normal events are not responsive enough, since the backend call somehow consumes so much time, they are not reacting in promptly fashion.
In my read methods I have added explicit checks – but I cannot add such checks in 3rd party frameworks. Also it is somehow not a very nice approach.
Maybe someone has an idea how to reliable and promptly stop some running methods. Is there an interrupt I can use?
Regards HW
Normal events are not responsive enough, since the backend call somehow consumes so much time
That's not how it works. Understand the "message loop" is pretty important, be sure to read up on it. In a nutshell, Windows can only tell your program that a button was clicked when the main thread of program is idle. Your main thread should always be idle, ready to jump into action when some bit of work needs to be done. Like painting your form or processing a keystroke. Or doing something when the user clicks the Cancel button.
Which means that something else needs to do the heavy lifting. A thread. By far the best way to get started in the troublesome world of threading is the BackgroundWorker class. It has a CancelAsync() method, explicitly designed to do what you want to do. Be sure to review the code sample provided in the MSDN Library article for this method.
Execute the long running code in a separate Thread.
Thread thread;
void StartLong()
{
thread = new Thread(SomeMethod);
thread.Start();
}
void SomeMethod()
{
//Long running code here.
}
void CancelButton_Click(object sender, EventArgs e)
{
//...
thread.Abort();
}
If you don't have control over the code that takes long to execute. All you can do do cancel it is to abort the thread. thread.Abort();
You should do "long" =eveything longer than 1/5sec operations in seperate threads.
The best way of topping an operation is giving it some kind of "context" with a variable wich tells the workerthread wether the user wants to abbord the operation or not.
If you have no control over the code doing the operation and the code is .net you may call Thread.Abort() but if the code is not .net the only thing you can do is callinfg the windows api function "terminatethread" but you may get some resource leaks and files not beeing closed so you should think of using a childprocess.
You may consider using the BackgroundWorker class, it abstracts out working directly with threads, so is a little easier to implement. You just create an instance of BackgroundWorker and attach some event handlers to it. Here is an example.

Multithreading: how to update UI to indicate progress

I've been working on the same project now since Christmas 2008. I've been asked to take it from a Console Application (which just prints out trace statements), to a full Windows App. Sure, that's fine. The only thing is there are parts of the App that can take several minutes to almost an hour to run. I need to multithread it to show the user status, or errors. But I have no idea where to begin.
I've aready built a little UI in WPF. It's very basic, but I'd like to expand it as I need to. The app works by selecting a source, choosing a destination, and clicking start. I would like a listbox to update as the process goes along. Much in the same way SQL Server Installs, each step has a green check mark by its name as it completes.
How does a newbie start multithreading? What libraries should I check out? Any advice would be greatly appreciated.
p.s. I'm currently reading about this library, http://www.codeplex.com/smartthreadpool
#Martin: Here is how my app is constructed:
Engine: Runs all major components in pre-defined order
Excel: Library I wrote to wrap COM to open/read/close/save Workbooks
Library: Library which understands different types of workbook formats (5 total)
Business Classes: Classes I've written to translate Excel data and prep it for Access
Db Library: A Library I've written which uses ADO.NET to read in Access data
AppSettings: you get the idea
Serialier: Save data in-case of app crash
I use everything from LINQ to ADO.NET to get data, transform it, and then output it.
My main requirement is that I want to update my UI to indicate progress
#Frank: What happens if something in the Background Worker throws an Exception (handled or otherwise)? How does my application recieve notice?
#Eric Lippert: Yes, I'm investigating that right now. Before I complicate things.
Let me know if you need more info. Currently I've running this application from a Unit Test, so I guess callig it a Console Application isn't true. I use Resharper to do this. I'm the only person right now who uses the app, but I'd like a more attractive interface
I don't think you specify the version of the CLR you are using, but you might check out the "BackgroundWorker" control. It is a simple way to implemented multiple threads.
The best part, is that it is a part of the CLR 2.0 and up
Update in response to your update: If you want to be able to update the progress in the UI -- for example in a progress bar -- the background worker is perfect. It uses an event that I think is called: ProgressChanged to report the status. It is very elegant. Also, keep in mind that you can have as many instances that you need and can execute all the instances at the same time (if needed).
In response to your question: You could easily setup an example project and test for your question. I did find the following, here (under remarks, 2nd paragraph from the caution):
If the operation raises an exception
that your code does not handle, the
BackgroundWorker catches the exception
and passes it into the
RunWorkerCompleted event handler,
where it is exposed as the Error
property of
System.ComponentModel..::.RunWorkerCompletedEventArgs.
Threading in C# from Joseph Albahari is quite good.
This page is quite a good summary of threading.
By the sound of it you probably don't need anything very complex - if you just start the task and then want to know when it has finished, you only need a few lines of code to create a new thread and get it to run your task. Then your UI thread can bumble along and check periodically if the task has completed.
Concurrent Programming on Windows is THE best book in the existence on the subject. Written by Joe Duffy, famous Microsoft Guru of multithreading. Everything you ever need to know and more, from the way Windows thread scheduler works to .NET Parallels Extensions Library.
Remember to create your delegates to update the UI so you don't get cross-threading issues and the UI doesn't appear to freeze/lockup
Also if you need a lot of notes/power points/etc etc
Might I suggest all the lecture notes from my undergrad
http://ist.psu.edu/courses/SP04/ist411/lectures.html
The best way for a total newcomer to threading is probably the threadpool. We'll probably need to know a little more about these parts to make more in depth recommendations
EDIT::
Since we now have a little more info, I'm going to stick with my previous answer, it looks like you have a loads of tasks which need doing, the best way to do a load of tasks is to add them to the threadpool and then just keep checking if they're done, if tasks need to be done in a specific order then you can simply add the next one as the previous one finishes. The threadpool really is rather good for this kind of thing and I see no reason not to use it in this case
Jason's link is a good article. Things you need to be aware of are that the UI can only be updated by the main UI thread, you will get cross threading exceptions if you try to do it in the worker thread. The BackgroundWorker control can help you there with the events, but you should also know about Control.Invoke (or Control.Begin/EndInvoke). This can be used to execute delegates in the context of the UI thread.
Also you should read up on the gotchas of accessing the same code/variables from different threads, some of these issues can lead to bugs that are intermittent and tricky to track down.
One point to note is that the volatile keyword only guarantees 'freshness' of variable access, for example, it guarantees that each read and write of the variable will be from main memory, and not from a thread or processor cache or other 'feature' of the memory model. It doesnt stop issues like a thread being interrupted by another thread during its read-update-write process (e.g. changing the variables value). This causes errors where the 2 threads have different (or the same) values for the variable, and can lead to things like values being lost, 2 threads having the same value for the variable when they should have different values, etc. You should use a lock/monitor (or other thread sync method, wait handles, interlockedincrement/decrement etc) to prevent these types of problems, which guarantee only one thread can access the variable. (Monitor also has the advantage that it implicitly performs volatile read/write)
And as someone else has noted, you also should try to avoid blocking your UI thread whilst waiting for background threads to complete, otherwise your UI will become unresponsive. You can do this by having your worker threads raise events that your UI subscribes to that indicate progress or completion.
Matt
Typemock have a new tool called Racer for helping with Multithreading issues. It’s a bit advanced but you can get help on their forum and in other online forums (one that strangely comes to mind is stackoverflow :-) )
I'm a newbie to multithreading as well, but I agree with Frank that a background worker is probably your best options. It works through event subscriptions. Here's the basics of how you used it.
First Instantiate a new background worker
Subscribed methods in your code to the background workers major events:
DoWork: This should contain whatever code that takes a long time to process
ProgressChanged: This is envoked whenever you call ReportProgress() from inside the method subscribed to DoWork
RunWorkerCompleted: Envoked when the DoWork method has completed
When you are ready to run your time consuming process you call the RunAsync() method of the background worker. This starts DoWork method on a separate thread, which can then report it's progress back through the ProgressChanged event. Once it completed RunWorkerComplete will be evoked.
The DoWork event method can also check if the user somehow requested that the process be canceled (CanceLAsync() was called)) by checking the value of the CancelPending property.

Categories

Resources