WindowBuilder update from paho callback (on MQTT Receive) [duplicate] - paho

I have a simple Java SWT app in Java so far but the weird thing is when I try to launch a messagebox/alert box upon listening to an event fired by one of my own classes, I get an error saying "Invalid thread access".
My class event is fired and heard by the main class but it is when it has to show the MessageBox that the "Invalid thread access" error appear. I am trying to show the MessageBox in a function that consist of all the other codes that will create the SWT GUIs. This is how the function looks like:
public void createContents() {
Shell shell = new Shell();
//.....all the SWT GUI codes....
MessageBox msg = new MessageBox(shell, SWT.OK);
myClass.addEventListener(new MyClassEventClassListener() {
#Override
public void myClassEventHandler(MyClassEvent e) {
msg.setText("Hello");
msg.setMessage("Event fired!");
int result = msg.open();
}
});
}
These are the auxiliary functions together in the class.
<!-- language: lang-java -->
protected static Shell shell;
public static void main(String[] args) {
MyClass new myClass = new MyClass();
try {
SWTApp window = new SWTApp();
window.open();
} catch (Exception e) {
}
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
The error stack trace is as follows:
Exception in thread "AWT-EventQueue-0" org.eclipse.swt.SWTException: Invalid thread access
at org.eclipse.swt.SWT.error(SWT.java:4083)
at org.eclipse.swt.SWT.error(SWT.java:3998)
at org.eclipse.swt.SWT.error(SWT.java:3969)
at org.eclipse.swt.widgets.Display.error(Display.java:1249)
at org.eclipse.swt.widgets.Display.checkDevice(Display.java:755)
at org.eclipse.swt.widgets.Display.getShells(Display.java:2171)
at org.eclipse.swt.widgets.Display.setModalDialog(Display.java:4463)
at org.eclipse.swt.widgets.MessageBox.open(MessageBox.java:200)
Any help will be great.
Thanks!

It is thrown because your listener code is called from outside the SWT Display thread. You run code on the display thread like this:
Display.getDefault().syncExec(new Runnable() {
public void run() {
// ...
}
});
or, asynchronously:
Display.getDefault().asyncExec(new Runnable() {
public void run() {
// ...
}
});

Maybe this will help you:
FAQ Why do I get an invalid thread access exception?
https://wiki.eclipse.org/FAQ_Why_do_I_get_an_invalid_thread_access_exception%3F

Related

SWT Dialog does not display correctly

When opening a new dialog, while its loading, you click couple of times on parent shell, apparently the new dialog does not display correctly.
Please see the example below:
Examples
https://i.stack.imgur.com/ZovxE.png (eclipse IDE example)
https://i.stack.imgur.com/5zVar.png
https://i.stack.imgur.com/u86b9.png
https://i.stack.imgur.com/FGaAr.png
Initially I encountered the problem in december 2014, and back then also reported by vaious in house devlopers which were using different development systems and then same problem has been reported by our several customers.
This behavior can be reproduced using following environment:
Windows Version: 7 Pro 64 Bit - 6.1.7601
Java Version: RE 1.8.0_121_b13
SWT Versions
3.8.2
4.6.2
4.7M6
I20170319-2000
I could only reproduce the problem on Windows 7 with the windows basic theme/design/style (not with classic or aero).
On windows 10 its not reproducible.
reproduce
code to reproduce
package test;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class Main {
public static void main(String[] args) {
Display display = new Display();
final Shell shell = createShell(display);
createButton(shell);
shell.open();
eventLoop(display, shell);
display.dispose();
}
private static Shell createShell(Display display) {
final Shell shell = new Shell(display);
shell.setLayout(new RowLayout());
shell.setSize(500, 200);
return shell;
}
private static void createButton(final Shell shell) {
final Button openDialog = new Button(shell, SWT.PUSH);
openDialog.setText("Click here to open Dialog ...");
openDialog.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TestDialog inputDialog = new TestDialog(shell);
inputDialog.open();
}
});
}
private static void eventLoop(Display display, final Shell shell) {
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
class TestDialog extends Dialog {
public TestDialog(Shell parent) {
super(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.MIN | SWT.MAX | SWT.RESIZE);
setText("Dialog");
}
public void open() {
Shell shell = new Shell(getParent(), getStyle());
shell.setText(getText());
createContents(shell);
shell.pack();
initializeBounds(shell);
shell.open();
eventLoop(shell);
}
private void createContents(final Shell shell) {
shell.setLayout(new GridLayout(2, true));
Label label = new Label(shell, SWT.NONE);
label.setText("Some Label text ...");
final Text text = new Text(shell, SWT.BORDER);
GridData data = new GridData(GridData.FILL_HORIZONTAL);
text.setLayoutData(data);
createCloseButton(shell);
/* time for the user to create the misbehavior */
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void createCloseButton(final Shell shell) {
Button closeButton = new Button(shell, SWT.PUSH);
closeButton.setText("Close");
GridData data = new GridData(GridData.FILL_HORIZONTAL);
closeButton.setLayoutData(data);
closeButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
shell.close();
}
});
shell.setDefaultButton(closeButton);
}
private void initializeBounds(Shell shell) {
Rectangle bounds = shell.getBounds();
Rectangle parentBounds = getParent().getBounds();
bounds.x = parentBounds.x;
bounds.y = parentBounds.y;
shell.setBounds(bounds);
}
private void eventLoop(Shell shell) {
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
steps to reproduce
Start the application
it should look like: https://i.stack.imgur.com/dMJ9e.png
Click on the button.
Keep continuously clicking on right bottom corner of the parent shell (avoid hitting the new opening dialog), till mouse cursor changes to wait icon and parent shell changes its color.
it should look as following: https://i.stack.imgur.com/c1Ikp.png
Wait until the new dialog appears.
it looks likes as following: https://i.stack.imgur.com/kTDgQ.png (incorrectly displayed)
instead: https://i.stack.imgur.com/cHVjn.png (correctly displayed)
steps to reproduce done in video
https://youtu.be/7ukhloCPf0k
When you mouse hover some of the UI elements (the originally not correctly drawn), you can notice some of them to be get painted (e.g. table rows).
https://i.stack.imgur.com/kkMKn.png (before opening the dialog)
https://i.stack.imgur.com/ZXIKc.png (after opening the dialog)
https://i.stack.imgur.com/25M7S.jpg (after mouse over)
Even calling Shell.update() or Shell.redraw() after the Dialog opened does not fix it.
In Windows Performance Options -> Visual Effects -> disable "Use visual styles on windows and buttons" is the only option I found which provides a workaround,
which seems to be the same as changing the design/theme/style to classic.
https://www.sevenforums.com/tutorials/1908-visual-effects-settings-change.html (How to Change Windows Visual Effects)
In the end, I have following questions:
Is it a SWT or Windows problem?
Is there any related topic in bug entries for Windows or in Eclipse Bugzilla?
Is there someone else who experienced the same problem? please share the experience.
Is there any settings in SWT or Windows which could affect its look n feel and fix the problem?
In the end, I have following questions: Is it a SWT or Windows problem?
Neither. As others have mentioned, you certainly should not tie up the UI thread with any long-running task. That work belongs in a background thread.
In regards to using a background thread, there are several ways you could go about this depending on how you want your Dialog to behave.
One option would be to kick off the background thread and then open the dialog when the task is done. I personally don't care for this because while the task is running, a user may think that nothing is happening.
Another option would be to open the dialog but display a "Loading" message, or something to that effect to give meaningful feedback and let a user know that the application isn't frozen (like how it looks/responds in your example).
The strategy would be to:
Create the dialog
Start the long task on a background thread and register a callback
Open the dialog with a "Loading" message
When the task is complete, the dialog will be updated from the callback
If you search around a bit on using Executors, you should find some far better examples and detail on how to use them.
Here's a brief example to illustrate what that might look like:
(Note: There are definitely a few issues with this code, but for the sake of brevity and illustrating the point I opted for a slightly naive solution. Also there are Java 8-esque ways that would be a bit shorter, but again, this illustrates the idea behind using a background thread; the same concepts apply)
Given a Callable (or Runnable if you don't need a return value),
public class LongTask implements Callable<String> {
#Override
public String call() throws Exception {
Thread.sleep(15000);
return "Hello, World!";
}
}
You can use the Executors class to create a thread pool, and then an ExecutorService to submit the Callable for execution. Then, using Futures.addCallback(), you can register a callback which will execute one of two methods depending on whether the task was successful or failed.
final ExecutorService threadPool = Executors.newFixedThreadPool(1);
final ListeningExecutorService executorService = MoreExecutors.listeningDecorator(threadPool);
final ListenableFuture<String> future = executorService.submit(new LongTask());
Futures.addCallback(future, new FutureCallback(){...});
In this case I used the Google Guava implementation ListeningExecutorService which makes things a bit cleaner and simpler, in my opinion. But again, you may not even need this if you opt for a more "Java 8" approach.
As for the callback, when the task is successful, we update the Dialog with the results. If it fails, we can update it with something to indicate failure:
public static class DialogCallback implements FutureCallback<String> {
private final MyDialog dialog;
public DialogCallback(final MyDialog dialog) {
this.dialog = dialog;
}
#Override
public void onSuccess(final String result) {
dialog.getShell().getDisplay().asyncExec(new Runnable() {
#SuppressWarnings("synthetic-access")
#Override
public void run() {
dialog.setStatus(result);
}
});
}
#Override
public void onFailure(final Throwable t) {
dialog.getShell().getDisplay().asyncExec(new Runnable() {
#SuppressWarnings("synthetic-access")
#Override
public void run() {
dialog.setStatus("Failure");
}
});
}
}
In this case I opted for the Callable to return a String, thus the FutureCallback should be parameterized with String. You may want to use some other class that you created, which will work just as well.
Notice that we use the Display.asyncExec() method to ensure that the code which updates the UI runs on the UI thread, because the callback may execute on the background thread.
Like I said, there are still a few issues here, including what happens when you click the cancel button before the task completes, etc. But hopefully this helps illustrate an approach for handling long-running background tasks without blocking the UI thread.
Full example code:
public class DialogTaskExample {
private final Display display;
private final Shell shell;
private final ListeningExecutorService executorService;
public DialogTaskExample() {
display = new Display();
shell = new Shell(display);
shell.setLayout(new GridLayout());
executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1));
final Button button = new Button(shell, SWT.PUSH);
button.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
button.setText("Start");
button.addSelectionListener(new SelectionAdapter() {
#SuppressWarnings("synthetic-access")
#Override
public void widgetSelected(final SelectionEvent e) {
final MyDialog dialog = new MyDialog(shell);
dialog.setBlockOnOpen(false);
dialog.open();
dialog.setStatus("Doing stuff...");
final ListenableFuture<String> future = executorService.submit(new LongTask());
Futures.addCallback(future, new DialogCallback(dialog));
}
});
}
public void run() {
shell.setSize(200, 200);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
executorService.shutdown();
display.dispose();
}
public static void main(final String... args) {
new DialogTaskExample().run();
}
public static class DialogCallback implements FutureCallback<String> {
private final MyDialog dialog;
public DialogCallback(final MyDialog dialog) {
this.dialog = dialog;
}
#Override
public void onSuccess(final String result) {
dialog.getShell().getDisplay().asyncExec(new Runnable() {
#SuppressWarnings("synthetic-access")
#Override
public void run() {
dialog.setStatus(result);
}
});
}
#Override
public void onFailure(final Throwable t) {
dialog.getShell().getDisplay().asyncExec(new Runnable() {
#SuppressWarnings("synthetic-access")
#Override
public void run() {
dialog.setStatus("Failure");
}
});
}
}
public static class LongTask implements Callable<String> {
/**
* {#inheritDoc}
*/
#Override
public String call() throws Exception {
Thread.sleep(15000);
return "Hello, World!";
}
}
public static class MyDialog extends Dialog {
private Composite baseComposite;
private Label label;
/**
* #param parentShell
*/
protected MyDialog(final Shell parentShell) {
super(parentShell);
}
/**
* {#inheritDoc}
*/
#Override
protected Control createDialogArea(final Composite parent) {
baseComposite = (Composite) super.createDialogArea(parent);
label = new Label(baseComposite, SWT.NONE);
return baseComposite;
}
public void setStatus(final String text) {
label.setText(text);
baseComposite.layout();
}
}
}
The code seems to be straight forward, only that you are making the main Thread sleep for 15secs hence the delay. If not required remove the sleep or reduce the time for sleep to 5secs or so.

Java 8 lambda catching exception

From the book Java 8 for the impatient by Cay Horstmann:
Didn’t you always hate it that you had to deal with checked
exceptions in a Runnable? Write a method uncheck that catches all
checked exceptions and turns them into unchecked exceptions. For
example,
new Thread(uncheck(
() -> { System.out.println("Zzz"); Thread.sleep(1000); })).start();
// Look, no catch (InterruptedException)!
Hint: Define an interface RunnableEx whose run method may throw any
exceptions. Then implement
public static Runnable uncheck(RunnableEx runner)
Use a lambda expression inside the uncheck function.
For which I code like this:
public interface RunnableEx {
void run() throws Exception;
}
public class TestUncheck {
public static Runnable uncheck(RunnableEx r) {
return new Runnable() {
#Override
public void run() {
try {
r.run();
} catch (Exception e) {
}
}
};
}
public static void main(String[] args) {
new Thread(uncheck(
() -> {
System.out.println("Zzz");
Thread.sleep(1000);
}
)).start();
}
}
Did I do according to what was hinted? Is there a better way of doing this?
Also there is another complementary question:
Why can’t you just use Callable<Void> instead of RunnableEx?
Your code fails to wrap the checked exception into an unchecked one. Further, it doesn’t following the hint to use a lambda expression. A corrected version would be:
public static Runnable uncheck(RunnableEx r) {
return () -> {
try {
r.run();
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
There are indeed possibilities to improve this further. Since the whole purpose of the RunnableEx interface is to wrap a Runnable, you could place the factory method inside the interface itself:
public interface RunnableEx {
void run() throws Exception;
public static Runnable uncheck(RunnableEx r) {
return () -> {
try {
r.run();
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
}
Of course, now your calling code has to be adapted to:
public static void main(String[] args) {
new Thread(RunnableEx.uncheck(
() -> {
System.out.println("Zzz");
Thread.sleep(1000);
}
)).start();
}
Now, the interface itself could implement the wrapping feature, becoming compatible with Runnable, which would eliminate the need to have a Runnable and a RunnableEx instance to represent a single action:
public interface RunnableEx extends Runnable {
void runWithException() throws Exception;
#Override default void run() {
try {
runWithException();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Runnable uncheck(RunnableEx r) {
return r;
}
}
Note that while the calling code doesn’t change syntactically, it will implicitly create a Runnable instance in the first place, when creating the RunnableEx instance, that’s why uncheck becomes a no-op, merely serving as a marker that a RunnableEx should be created rather than a Runnable. With this interface definition, you could achieve the same via
public static void main(String[] args) {
new Thread( (RunnableEx) () -> {
System.out.println("Zzz");
Thread.sleep(1000);
}
).start();
}
The reason why you can’t “just use” a Callable<Void> here, is that Callable<Void> still is a Callable, requiring the implementation code to return a value. In other words, there is no implicit conversion from void to Void. So you can use it, but the lambda expression would require a return null; statement at its end then (null is the only value compatible with Void).
public class TestUncheck {
public static Runnable uncheck(Callable<Void> r) {
return () -> {
try { r.call(); }
catch (Exception e) { throw new RuntimeException(e); }
};
}
public static void main(String[] args) {
new Thread(uncheck(
() -> {
System.out.println("Zzz");
Thread.sleep(1000);
return null;
}
)).start();
}
}
This way of catching exceptions from lambdas works fine, and is (with a few additions) the one implemented in the Unchecked class from jOOλ, a popular Java library.
For comparison, see their static method Unchecked.runnable, which is identical to your solution, with the exception of their Exception handler and to the lambda abreviating the return value.
With regards to the assignment from Java 8 to the Impatients, your uncheck method does not use a lambda (for this, see the Unchecked.runnable method), and does not throw an unchecked exception. For this, your catchblock (currently empty) needs to wrap the exception into an unchecked exception. There are many ways to do it, and many questions on SO are relevant:
How to wrap checked exceptions but keep the original runtime exceptions in Java
Replace a checked exception with a runtime exception?
Handling Runtime exception in Java
But a simple way is:
throw (e instanceof RuntimeException) ? (RuntimeException) e : new RuntimeException(e);
Finally, to answer the Callable<Void>question, I am assuming you mean "instead of Runnable"? If so, it is because the constructors from Thread take a Runnableas an argument.

How to enable and disable a progress indicator when using JMS in javafx8

on action i send a message to a jms topic to process data and i have a call back method which gets called when the data is ready and loads a TableView.
public void onEnter(ActionEvent actionEvent) throws IOException, InterruptedException {
new Thread() {
public void run() {
Platform.runLater(() -> {
progressIndicator.setVisible(true);
scrollPane.setDisable(true);
});
// Construct the message and publish it to a topic
};
}.start();
}
}
public void callBackMethod(List<Object> list ) {
progressIndicator.setVisible(false);
scrollPane.setDisable(false);
//load data in the table
}
This does what i want, but what if something goes wrong at the messaging system end , the call back never gets called and the UI component will be disabled forever .
Any suggestions to improve this will be helpful.
Presumably, the messaging system is going to throw some kind of exception if it fails to send the message, so you'll need a way to catch that and recover properly. If you use the JavaFX "Task" class, then you'll get events when that happens. You'll still have to deal with a failure at the receiving end, or implement some kind of a time-out, if that's appropriate.
Also, you're starting up a thread and then immediately tossing a job onto the FXAT with RunLater. The onEnter event handler, by definition, is already running on the FXAT, so you can just do your GUI stuff before you start up the thread (or Task, as I suggest). Here's a sample that shows how to launch the Task, and clean up if it fails with an exception:
public class SampleTask extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
BorderPane root = new BorderPane();
ProgressIndicator progressIndicator = new ProgressIndicator(0);
ScrollPane scrollPane = new ScrollPane();
Button button = new Button("Start");
root.setTop(progressIndicator);
root.setCenter(scrollPane);
progressIndicator.setVisible(false);
root.setBottom(button);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
button.setOnAction(actionEvent -> {
progressIndicator.setVisible(true);
scrollPane.setDisable(true);
Task<Void> testTask = new Task<Void>() {
#Override
protected Void call() throws Exception {
// Send the message
return null;
}
};
testTask.setOnFailed(event -> {
progressIndicator.setVisible(false);
scrollPane.setDisable(false);
});
new Thread(testTask).start();
});
}
}

Android basics: running code in the UI thread

In the viewpoint of running code in the UI thread, is there any difference between:
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
or
MainActivity.this.myView.post(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
and
private class BackgroundTask extends AsyncTask<String, Void, Bitmap> {
protected void onPostExecute(Bitmap result) {
Log.d("UI thread", "I am the UI thread");
}
}
None of those are precisely the same, though they will all have the same net effect.
The difference between the first and the second is that if you happen to be on the main application thread when executing the code, the first one (runOnUiThread()) will execute the Runnable immediately. The second one (post()) always puts the Runnable at the end of the event queue, even if you are already on the main application thread.
The third one, assuming you create and execute an instance of BackgroundTask, will waste a lot of time grabbing a thread out of the thread pool, to execute a default no-op doInBackground(), before eventually doing what amounts to a post(). This is by far the least efficient of the three. Use AsyncTask if you actually have work to do in a background thread, not just for the use of onPostExecute().
I like the one from HPP comment, it can be used anywhere without any parameter:
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
There is a fourth way using Handler
new Handler().post(new Runnable() {
#Override
public void run() {
// Code here will run in UI thread
}
});
The answer by Pomber is acceptable, however I'm not a big fan of creating new objects repeatedly. The best solutions are always the ones that try to mitigate memory hog. Yes, there is auto garbage collection but memory conservation in a mobile device falls within the confines of best practice.
The code below updates a TextView in a service.
TextViewUpdater textViewUpdater = new TextViewUpdater();
Handler textViewUpdaterHandler = new Handler(Looper.getMainLooper());
private class TextViewUpdater implements Runnable{
private String txt;
#Override
public void run() {
searchResultTextView.setText(txt);
}
public void setText(String txt){
this.txt = txt;
}
}
It can be used from anywhere like this:
textViewUpdater.setText("Hello");
textViewUpdaterHandler.post(textViewUpdater);
As of Android P you can use getMainExecutor():
getMainExecutor().execute(new Runnable() {
#Override public void run() {
// Code will run on the main thread
}
});
From the Android developer docs:
Return an Executor that will run enqueued tasks on the main thread associated with this context. This is the thread used to dispatch calls to application components (activities, services, etc).
From the CommonsBlog:
You can call getMainExecutor() on Context to get an Executor that will execute its jobs on the main application thread. There are other ways of accomplishing this, using Looper and a custom Executor implementation, but this is simpler.
If you need to use in Fragment you should use
private Context context;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
((MainActivity)context).runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
instead of
getActivity().runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
Because There will be null pointer exception in some situation like pager fragment
use Handler
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// Code here will run in UI thread
}
});
Kotlin version:
Handler(Looper.getMainLooper()).post {
Toast.makeText(context, "Running on UI(Main) thread.", Toast.LENGTH_LONG).show()
}
Or if you are using Kotlin coroutines:
inside coroutine scope add this:
withContext(Dispatchers.Main) {
Toast.makeText(context, "Running on UI(Main) thread.", Toast.LENGTH_LONG).show()
}

Live SDK Windows Phone 7 GetCompleted callback in UI thread?

public class SyncHelper
{
private LiveConnectClient client;
public event EventHandler SyncStarted;
public event EventHandler SyncCompleted;
public SyncHelper(LiveConnectClient client)
{
this.client = client;
}
public void TrySync()
{
Debug.WriteLine("Beginning sync");
OnSyncStarted();
client.GetCompleted += OnGetCompleted;
client.GetAsync("me/skydrive/files");
}
private void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
Thread.Sleep(10000);
Debug.WriteLine("Get Completed");
client.GetCompleted -= OnGetCompleted;
OnSyncCompleted();
Debug.WriteLine("Sync completed");
}
private void OnSyncStarted()
{
if (SyncStarted != null)
SyncStarted(this, new EventArgs());
}
private void OnSyncCompleted()
{
if (SyncCompleted != null)
SyncCompleted(this, new EventArgs());
}
}
The function OnGetCompleted is being called in the UI thread and the UI is unresponsive. From whatever I know, I thought these callbacks would work in a different thread and we would have to use the displatcher to post it to the UI thread. Any thoughts? Help!
The GetAsync call is likely using a background thread to do the actual fetch, but then it's trying to help you by calling the Completed callback in the original thread context so you don't have to use a Dispatcher.
Why are you putting in a Sleep(10000) anyway? The callback says "hey, I'm done". At that point you should update the UI if you want. If you need to do further processing that takes significant time, spawn a background thread, threadpool task or use another asynchronous call with another callback.

Resources