Lightswitch task on a background thread - multithreading

I have a lightswitch app which sends an email when a new job is added. I added a sendemail helper class which is called when the record is inserted.
This works however the interface hangs on save waiting for the email to be sent.
I would like to perform this asychronously so that the user can go on and do his thing while the email sends in the background.
I've tried creating a new thread in the inserted part, hoping it would spin off the thread and then return to the user, but it doesn't work, it is still waiting for the thread to finish.
Thread caseemail = new Thread(new ParameterizedThreadStart(newSendmail.generateCaseEmail));
string[] paramsToPass = new String[] { entity.ProjectNumber, entity.CreatedBy, entity.TheProjectClientManagerFixed, entity.ProjectName };
caseemail.Start(paramsToPass);
How should I be doing this?

So in the end this code works, the errors were from problems access dataworkspaces from the other thread, which is obviously not allowed.
I will leave this here as an example of how to spin off a task into the background from lightswitch, leaving the interface responsive while lightswitch goes away and does something else.

Related

IsolatedStorageSettings freeze UI thread WP8

in my app when a user logs in to skydrive and the status changes I am changing 4 settings in IsolatedStorageSettings.
It is done the same as http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769510(v=vs.105).aspx
When I modify these 4 values though my UI thread is freezing for a second or two as my progress bar gets choppy. I tried running it in a thread like so but still the same issue.
Thread ContactThread = new Thread(new ThreadStart(UpdateContact));
ContactThread.Start();

JavaFX2: Can I pause a background Task / Service?

I am trying to set up a background service that would perform bulk loading of transaction data from a csv file. This background service would be initiated from a menu item action mapped to a method in the controller/presenter class.
Ever so often, some data turns up in the csv file for which no master data can be found in the database, this would normally cause the upload to choke and fail.
On such occasions, I would like to be able to have the background service pause its processing and invoke a dialog from a presenter class to take in user input. The user input would be used to add a master row in the database, after which the background service should resume from where it had left off (not from the beginning of the csv file, but from the row which caused the error).
Is this possible to achieve in JavaFX, perhaps with the javafx.concurrent API? How would I go about doing this?
Solution
When your background process encounters a situation where it requires a user to be prompted for input, use FutureTask executed in Platform.runLater to showAndWait the dialog prompt on the JavaFX application thread. In the background process use futureTask.get to pause the background process until the user has input the necessary values which will allow the process to continue.
Sample Code Snippet
Here is the essence of code for this approach which can be placed inside the call method of your background process:
String nextText = readLineFromSource();
if ("MISSING".equals(nextText)) {
updateMessage("Prompting for missing text");
FutureTask<String> futureTask = new FutureTask(
new MissingTextPrompt()
);
Platform.runLater(futureTask);
nextText = futureTask.get();
}
...
class MissingTextPrompt implements Callable<String> {
private TextField textField;
#Override public String call() throws Exception {
final Stage dialog = new Stage();
dialog.setScene(createDialogScene());
dialog.showAndWait();
return textField.getText();
}
...
}
Sample Application
I created a small, complete sample application to demonstrate this approach.
The output of the sample application is:
Sample Output Explanation
Lines read without missing values are just plain brown.
Lines with a prompt value entered have a pale green background.
Fourteen lines have been read, the background task has already paused once at the 6th line which was missing a value. The user was prompted for the missing value (to which the user entered xyzzy), then the process continued until line 14 which is also missing and the background task is again paused and another prompt dialog is being displayed.

How to handle network thread calls and wait progress in J2me?

In my project I have created some network calls to the servlets in separate Thread where before that thread starts I show a spinner as wait progress. Until that network Thread finishes the waitprogress is displayed on to the screen and when I receive response from the server I have to explicitly call progress bar's dispose() method to dispose that progress bar. So, This is bit complicated whenever I make calls establishing GPRS connection while network strength goes down there I found sometimes it takes about 2-3 minutes to throw an IO Exception or receive response from server where I dispose waitprogress, show error message and proceed. I dont add any cancel command to waitprogress as network calls are made using separate thread so disposing waitprogress will allow user to make another call where the user is needed to wait until he gets response.
The above scenario is complicated because the user will not be waiting for this long to get response. There must be some way that whenever I call network Thread and show progress bar the user should be able to cancel all the operations including network thread, go back to previous state and make another call if there is no or poor connectivity.
Here, I am using Lwuit.
In NetworkManager class you can add this function and actived at from your class
only if lwuit is at open code in your application , you can add this function:
public void killAll() {
for (int i = 0; i < pending.size(); i++) {
((ConnectionRequest) pending.elementAt(i)).kill();
}
pending.removeAllElements();
for (int i = 0; i < networkThreads.length; i++) {
networkThreads[i].currentRequest.kill();
}
}
after or before this you need call dispose() method.

My Java thread stops at "OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());" w/o any error?

So I am currently writing a program used to access a website and retrieve information.
The functional part of the program lies as follows:
URL url = new URL("website name");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
I am trying to use threads to implement this program, so that each new thread created will open up a new connection. I have already tested this program separately from a thread and this code works perfectly fine, but the moment that place this code into the run() method of my Thread class, it stops working.
I placed print statements after every single line of code, to give me an idea as to where the program was stopping and the last sign of life is consistently "setDoOutput(true)" and nothing happens after that. No errors, no nothing, the program just stops.
What is going on?

MFC dialog frozen

I need help how to unfreeze my dialog box. I'm using MFC and I have an infinite loop I want to execute when a button is pressed. However, the dialog box freezes when the infinite loop starts. Now I looked at this thread where someone was having a similar problem.
Unfortunately I tried multithreading but I found out that It can't work for me because I'm using an api that uses OLE automation and I'm getting an unhandled memory exception. I think this is because program uses the serial port and i read somewhere you can only use the handle to the serial port in one thread.
My program is simply to see if someone has dialed in to my modem and wait for them to send me a file, then hangup. Here is my loop.
while(1)
{
//get rid of input buffer
ts->_this->m_pHAScript->haReleaseRemoteInput();
ts-> _this->textBox->SetWindowTextA("thread Commence");
//wait for connected
if(success = ts->_this->m_pHAScript->haWaitForString("CONNECT",timeout))
{
//getFile
if(success = ts->_this->m_pHAScript->haWaitForXfer(5000))
{
//hangup
ts->_this->haTypeText("+++ath\r");
}
}
}
Is there a way to unfreeze the dialog box?
Add this code inside while loop:
MSG msg;
while(PeekMessage(&msg, GetSafeHwnd(), 0, 0, PM_REMOVE))
{
DispatchMessage(&msg);
}
The GUI in Windows relies on a message loop - somewhere in your code, either explicitly or hidden in a framework, there's a loop that checks for a message in a queue and processes it. If anything blocks the code from returning to that loop, the GUI gets frozen.
There are a few ways around this. One was given by David Brabant, essentially duplicating the loop. Another is to start a new "worker" thread that runs the blocking operation independently. If your message loop has a function that it calls when it is idle, i.e. no more messages are in the queue, you can do some processing there; that's not possible in your example however.

Resources