I'm trying to set a textview's text from other thread than the main one,so I've written in the constructor:
Thread myth = new Thread (new ThreadStart (set_txt));
myth.Start ();
and of course set_txt is a method contains
textview1.Buffer.Text = "Whatever";
The probleme is that When I run the code most time it stops and gives an error:
=================================================================
Got a SIGSEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.
=================================================================
What should I do??
You need to update the GTK# text view from the GUI thread. You can do this by using Gtk.Application.Invoke:
Gtk.Application.Invoke (delegate {
textview1.Buffer.Text = "Whatever";
});
You need to update the UI from the UI thread. Just use Gtk.Application.Invoke passing it a lambda or a delegate:
Gtk.Application.Invoke(() => { textview1.Buffer.Text = "Whatever"; });
Related
This question already has answers here:
How do I update the GUI from another thread?
(47 answers)
Closed 1 year ago.
Currently I am creating a background STA thread to keep the UI responsive but it slows down my function calls on the main thread.
Based on this thread How to update progress bar while working in the UI thread I tried the following but the UI only gets updated after all of the work has finished. I tried playing around with the Dispatcher priorities but none of them seem to work.
What I also tried is adding _frmPrg.Refresh() to my Progress callback but this does not seem to change anything.
Dim oProgress = New Progress(Of PrgObject)(Sub(runNumber)
_frmPrg.Invoke((Sub()
_frmPrg.Status = runNumber
End Sub))
End Sub)
System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(Sub()
DoLongRunningWork(oProgress, _cancellationToken)
End Sub, System.Windows.Threading.DispatcherPriority.Background)
I can't really help you with your problem, but I'll try to clarify what happens in your posted code.
DoLongRunningWork will be invoked through Dispatcher on the UI thread, when the UI thread is not busy. But once started, it will block the UI thread until it completes. So you can't show a progress this way. Your single chance is, to let DoLongRunningWork run on a background thread. That brings you nothing, if the long-running methods come from office objects, which must be accessed from the UI thread...
The Progress class (see the remarks section) invokes your event handler on the UI thread automatically, so you don't need _frmPrg.Invoke in your event handler.
Maybe you can start a STAthread for your progress form and show it from there. The instance of your Progress class must be created in this thread too, but not before your form is shown to ensure, that the thread becomes a WindowsFormsSynchronisationContext (or you set one explicitly after starting the thread). A plain SynchronisationContext won't work!
At least you get updates in your form this way, but the UI thread of the office app will still be blocked. And of course, any action you make with your progress form must be invoked on the UI thread, if accessing office objects.
After reading some other posts, I decided to suggest another solution. My previous answer still contains usable information, so I'll leave it there. I'm not familiar with VB.NET syntax, so the samples are in C#. I have tested the code in a VSTO plugin for PowerPoint, but it should run in any office application.
Forget the Progress class and background threads. Run everything on the UI thread!
Now use some async code. To stay on the UI thread, we need a "good" SynchronizationContext.
private static void EnsureWinFormsSyncContext()
{
// Ensure that we have a "good" SynchronisationContext
// See https://stackoverflow.com/a/32866156/10318835
if (SynchronizationContext.Current is not WindowsFormsSynchronizationContext)
SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
}
This is the event handler of a button. Note the manually added async keyword. The SynchronizationContext.Current gets resetted again and again, so ensure the good one in the EventHandler:
private async void OnButtonClick(object sender, EventArgs e)
{
EnsureWinFormsSyncContext();
// Return from event handler, ensure that we are really async
// See https://stackoverflow.com/a/22645114/10318835
await Task.Yield();
await RunLongOnUIThread();
}
This will be the worker method, also running on the UI thread.
private async Task RunLongOnUIThread()
{
//Dummy code, replace it with your code
var pres = addIn.Application.Presentations.Add();
for (int i = 0; i < 100; i++)
{
Debug.Print("Creating slide {0} on thread {1}", i, Thread.CurrentThread.ManagedThreadId);
// If you have some workloads that can be run on a background
// thread, execute them with await Task.Run(...).
try
{
var layout = pres.Designs[1].SlideMaster.CustomLayouts[1];
var slide = pres.Slides.AddSlide(i + 1, layout);
var shape = slide.Shapes.AddLabel(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal, 0, 15 * i, 100, 15);
shape.TextFrame.TextRange.Text = $"Text on slide {i + 1}";
}
catch (Exception ex)
{
Debug.Print("I don't know what am I doing here, I'm not familiar with PowerPoint... {0}", ex);
}
// Update UI
statusLabel.Text = $"Slide {i + 1} done";
progressBar1.Value = i + 1;
// This is the magic! It gives the main thread the opportunity to update the UI.
// It also processes input messages so you need to disable unwanted buttons etc.
await IdleYield();
}
}
The following method is for Windows Forms Applications where it does the job perfect. I've tried it also in PowerPoint. If you are facing problems, try the WPF flavour with await Dispatcher.Yield(DispatcherPriority.ApplicationIdle) instead of await IdleYield().
private static Task IdleYield()
{
var idleTcs = new TaskCompletionSource<bool>();
void handler(object s, EventArgs e)
{
Application.Idle -= handler;
idleTcs.SetResult(true);
}
Application.Idle += handler;
return idleTcs.Task;
}
Here are the (clickable) links to the answers that I used (I can't put them in the code-blocks...).
Incorrect async/await working, Excel events in Excel Application Level Add-in
When would I use Task.Yield()?
Task.Yield - real usages?
If in your real code something runs not as expected, check the thread you are running on and SynchronizationContext.Current.
I was trying to update the recycler view content from a background thread in Kotlin. I am not using AsyncTask.
Here is my code, i want to know if there is any better way than this:
In my MainActivity, i have progressThread as a member variable.
var progressThread = Thread()
Then in my method where i want to run the thread first i am defining it...like
progressThread = Thread (
Runnable {
kotlin.run {
try {
while (i <= 100 && !progressThread.isInterrupted) {
Thread.sleep(200)
//Some Logic
runOnUiThread {
//this runs in ui thread
}
i++
}
}catch (e:InterruptedException){
progressThread.interrupt()
}
}
})
after that i am starting it in the same method as
progressThread.start()
and for stopping it, i have a listener to cancel the progress and in the callback of that listener, i have written:
progressThread.interrupt()
Updated
Coroutines are stable now,: https://kotlinlang.org/docs/reference/coroutines-overview.html
Old Answer
Yes, you can do this using doAsync from kotlin anko library that is fairly simple and easy to use.
add following line in module level gradle file:
compile "org.jetbrains.anko:anko-commons:0.10.0"
Code example:
val future = doAsync {
// do your background thread task
result = someTask()
uiThread {
// use result here if you want to update ui
updateUI(result)
}
}
code block written in uiThread will only be executed if your Activity or Fragment is in foreground mode (It is lifecycle aware). So if you are trying to stop thread because you don't want your ui code to execute when Activity is in background, then this is an ideal case for you.
As you can check doAsync returns a Future object so you can cancel the background task, by cancel() function:
future.cancel(true)
pass true if you want to stop the thread even when it has started executing.
If you have more specialised case to handle stopping case then you can do the same thing as in your example.
You can use Kotlin Coroutines also but its in Experimental phase, still you can try it out: https://kotlinlang.org/docs/reference/coroutines.html
I am trying for days now to find a proper solution to the following problem(stated below), and I have no more ideas now. Therefore, I need help from more experienced devs:
I have a class independant from QT (and I want it to stay like this) that generate openCV images in a secundary thread. Then it raise an event which pass the images.
while (1)
{
if (timerActived & this->_camReady)
{
vector<Mat>* images = new vector<Mat>;
images = this->AcquireImg();
__raise this->frameAcquired(images);
}
this_thread::sleep_for(chrono::milliseconds(_frameTimeLaps));
}
This event is hooked by my MainWindow and a method is supposed to display my images on my GUI.
void MainWindow::displayFrame(vector<Mat>* frames) {
vector<Mat>* frames2 = new vector<Mat>();
frames2 = frames;
for (int i = 0; i < frames2->size(); ++i) {
this->camFrames->at(i)->showImage(frames2->at(i));
}
}
During the runTime, when the Main Thread access the images I get the following error :
ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread.
I understand that I am not using threads properly, but I have no idea how to create an asynchronous event now.
Thank you for help,
Valentin
EDIT 1 :
It seems to me that the real question is : can I use normal std::thread and native event to communicate with the main Qthread ?
Here is my solution to solve the problem, after all.
The idea is to give the main thread access to the Mat coming from the second thread. So I modified my function displayFrame like this :
void MainWindow::displayFrame(vector<Mat>* frames) {
//QThread::
QThread* this_thread = QThread::currentThread();
FrameWrapper* worker = new FrameWrapper();
worker->moveToThread(this_thread);
QObject::connect(worker, SIGNAL(frameSent(vector<Mat>*)), this, SLOT(showImg(vector<Mat>*)));
emit worker->frameSent(frames);
//this->camFrames->at(0)->showImage(frame);
}
The new function showImg is doing the job of the old displayFrame. The signal/slot process permit to access image from the GUI Thread as wanted.
I would like to create a custom FunctionPlotter component that is based on the JavaFx WebEngine. My plots will be shown in a browser. Before I execute my plot commands I have to wait until the browser has been initialized (it loads d3.js). Currently I do so by putting my plot expressions in a Runnable and pass that runnable to the FunctionPlotter. (The FunctionPlotter passes the runnable to the loading finished hook of the browser):
private FunctionPlotter plotter;
...
Runnable plotRunnable = ()->{
plotter.plot("x^2");
}
plotter = new FunctionPlotter(plotRunnable);
However I would prefer following (blocking) work flow for the usage of my FunctionPlotter component:
Functionplotter plotter = new FunctionPlotter();
plotter.plot("x^2")
=> The FunctionPlotter should automatically wait until the wrapped browser has been initialized.
How should I do this in an JavaFx Application?
Inside the FunctionPlotter I could do something like
private Boolean isInitialized = false
...
ReadOnlyObjectProperty<State> state = webEngine.getLoadWorker().stateProperty();
state.addListener((obs, oldState, newState) -> {
boolean isSucceeded = (newState == Worker.State.SUCCEEDED);
if (isSucceeded) {
isInitialized = true;
}
});
webEngine.loadContent(initialBrowserContent);
waitUntilInitialLoadingIsFinished();
My actual question is how the method on the last line could be implemented. If I use following code, the application will wait for ever:
private void waitUntilBrowserIsInitialized() {
while(!isInitialized){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
I know that there is stuff like JavaFx Tasks, Platform.runLater(), Service, CountdownLatch (JavaFX working with threads and GUI) but those did not help me (= I did not get it working). How can I wait in the main Thread until a Runnable is finished?
Here someone says that the JavaFx Application thread should never be blocked:
Make JavaFX application thread wait for another Thread to finish
Any other suggestions?
Edit
Related question: JavaFX/SWT WebView synchronous loadcontent()
I decided to wrap the plot functionality in an internal queue of plot instructions. The command
plotter.plot("x^2");
will not actually execute the plot but add a plot instruction to the queue. After the browser has been initialized, that queue will be worked through and the plot commands will be executed with a delay. While the browser is initializing I will show some kind of progress bar.
If you know a solution that does not need this delayed execution work around please let me know.
I suddenly get hundreds of these lines in my console log running a process which uses a progress controller I implemented:
** __NSAutoreleaseNoPool(): Object 0x7afafd0 of class NSCFString autoreleased with no pool in place - just leaking
** __NSAutoreleaseNoPool(): Object 0xd8ca4a0 of class __NSCFData autoreleased with no pool in place - just leaking
I'm in a multithreaded environment on iPhone Simulator, downloading a file from the web using WebClient(). I am puzzled how to deal with this as I have no idea what might cause the problem. The thread that is running the download is embedded in
using ( var oAutoRelease = new NSAutoreleasePool ( ) )
I'm attaching to the WebClient's DownloadProgressChanged method and in there I call a delegate which updates the progress view. If I remove this line, the warnings are gone:
ProgressInfo(ACTION.ReceivingResponse, e.ProgressPercentage);
Calling the delegate in turns will go back to my progress controller and udpate a label:
// iIndicator = the value of e.ProgressPercentage.
oProgressController.CurrentActivity = "Percentage done: " + iInidicator.ToString ( ) + "%";
// ProgressController.CurrentActivity:
this.InvokeOnMainThread(delegate { this.oLblCurrentActivity.Text = value; });
What am I missing here!?
EDIT: I figured out that I had to put another NSAutoReleasePool() around this.InvokeOnMainThread(delegate { this.oLblCurrentActivity.Text = value; });
But why? The whole thing is already in a separate pool.
This link should help you http://blog.datispars.com/tasks-in-background-thread-cocoa-performselectorinbackground/
Each thread should have it's own autorelease pool