I need to execute a method (not process) asynchronously in my Perl code, but I must ensure that this code will never raise any exception and stop my main task execution.
What would be the best way to call a method asynchronously and silencing any potential exception whether it is the called method internal exception whether it is an threading exception?
In Java we would had something like this:
// my task runs here
try {
// assyncrounous method invocation (fire and forget)
new MyThread().start();
} catch (Throwable e) {
// Silent any error
}
// my task continues here
You have two options if you want to execute arbitrary code asynchronously: You can run it in a separate process, or you can run it in a separate thread. Using a separate process would make even more robust, but you could use a thread.
use threads;
my $thread = async { code() };
join the thread to wait for it to finish.
Related
I have a slice of struct that defines a task, each task is run in a goroutine, and I want all go goroutines to stop whenever the first one complete a task via the signal task.signalComplete
Currently I have the following.
for _, task := range taskList {
go func(task *myTask, firstCompleteSignal chan<- bool) {
for {
select {
// When the task completes, it emit signalComplete
case <-task.signalComplete:
firstCompleteSignal<-true
return
}
}
}(task, firstCompleteSignal)
}
for {
select {
case <-firstCompleteSignal:
// manually stop all go thread
return
}
}
Is this canonical?
Or is there library to do this for me like sync.WaitGroup for waiting all goroutine to be done?
The common idiom is to have a Done channel shared between the calling code and the goroutines.
Then each goroutine would check that channel via a select each time they
send a new value to the calling code.
You can find a good example in Go's blog:
https://blog.golang.org/pipelines
(look for "Explicit Cancellation" there)
Later, they incorporated a context package to the standard library, and that is now the most "standard" way to manage cancellation of goroutines.
You can find a good example in the documentation for the package itself:
https://golang.org/pkg/context/#example_WithCancel
I would like someone to explain to me what is Device.BeginInvokeOnMainThread and what is it for?
And also some examples of cases where it's used.
Just to add an example.
Imagine you have an async method DoAnyWorkAsync if you call it (just as an example) this way:
DoAnyWorkAsync().ContinueWith ((arg) => {
StatusLabel.Text = "Async operation completed...";
});
StatusLabel is a label you have in the XAML.
The code above will not show the message in the label once the async operation had finished, because the callback is in another thread different than the UI thread and because of that it cannot modify the UI.
If the same code you update it a bit, just enclosing the StatusLabel text update within Device.BeginInvokeOnMainThread like this:
DoAnyWorkAsync().ContinueWith ((arg) => {
Device.BeginInvokeOnMainThread (() => {
StatusLabel.Text = "Async operation completed...";
});
});
there will not be any problem.
Try it yourself, replacing DoAnyWorkAsync() with Task.Delay(2000).
The simple answer is: Background thread cannot modify UI elements because most UI operations in iOS and Android are not thread-safe; therefore, you need to invoke UI thread to execute the code that modifies UI such MyLabel.Text="New Text".
The detailed answer can be found in Xamarin document:
For iOS:
IOSPlatformServices.BeginInvokeOnMainThread() Method simply calls NSRunLoop.Main.BeginInvokeOnMainThread
public void BeginInvokeOnMainThread(Action action)
{
NSRunLoop.Main.BeginInvokeOnMainThread(action.Invoke);
}
https://developer.xamarin.com/api/member/Foundation.NSObject.BeginInvokeOnMainThread/p/ObjCRuntime.Selector/Foundation.NSObject/
You use this method from a thread to invoke the code in the specified object that is exposed with the specified selector in the UI thread. This is required for most operations that affect UIKit or AppKit as neither one of those APIs is thread safe.
The code is executed when the main thread goes back to its main loop for processing events.
For Android:
Many People think on Xamarin.Android BeginInvokeOnMainThread() method use Activity.runOnUiThread(), BUT this is NOT the case, and there is a difference between using runOnUiThread() and Handler.Post():
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);//<-- post message delays action until UI thread is scheduled to handle messages
} else {
action.run();//<--action is executed immediately if current running thread is UI thread.
}
}
The actual implementation of Xamarin.Android BeginInvokeOnMainThread() method can be found in AndroidPlatformServices.cs class
public void BeginInvokeOnMainThread(Action action)
{
if (s_handler == null || s_handler.Looper != Looper.MainLooper)
{
s_handler = new Handler(Looper.MainLooper);
}
s_handler.Post(action);
}
https://developer.android.com/reference/android/os/Handler.html#post(java.lang.Runnable)
As you can see, you action code is not executed immediately by Handler.Post(action). It is added to the Looper's message queue, and is handled when the UI thread's scheduled to handle its message.
You can only update the UI from the main UI thread. If you are running code on a background thread and need to update the UI, BeginInvokeOnMainThread() allows you to force your code to run on the main thread, so you can update the UI.
As explained above, any UI updates must happen in the main thread or an exception will occur.
Though there's a peculiarity with Xamarin.Forms, one can manilpulate UI elements (e.g. create Labels and add them to StackLayout's Children collection) off the main thread without any failures as long as this part of UI is detached from UI elements currently displayed. This approach can be used to boost performance by creating Xamarin.Forms controls and setting their child/parent relations in-memory/off-screen in a separate thread BUT in order to attach them to displayed container (e.g. assign ContentPage's Content property) you will have to do this in Device.BeginInvokeOnMainThread().
While analysing the relationship between UI thread and background thread in some situation, we should be aware of the following:
BeginInvokeOnMainThread method as described in the docs, merely queues the invocation and returns immediately to the caller. So in this case, UI thread and background thread which submitted some work to UI thread, might work in parallel.
However, there is also InvokeOnMainThread which, as described in the docs, waits for the UI thread to execute the method, and does not return until the code pointed by action has completed. So in this case, background thread waits for UI thread to finish executing the given work, and then background thread continues execution.
I want to pause /resume my webdriver test case execution on press of a button.
The way i come up is to use Thread class suspend and resume methods. But i want to make sure that it should not pause while webdriver is typing text or something. As if it will do the browser may loose the focus from that point. So i want to ensure atomic execution of element.sendKeys or element.click.
Please suggest any ideas???
Just run the test in debug mode. Then you can just suspend the entire JVM. This will have the effect of pausing WebDriver.
I think your best option here is to implement your own synchronization and start/stop around Selenium. One way to achieve this is to protect every call to a WebDriver API method with a monitor and a boolean flag to indicate that some other instance would like to suspend test execution:
private boolean suspend = false;
private Object monitor = new Object();
Your code before each API call could look as follows:
synchronized (monitor) {
if (suspend) {
try {
monitor.wait();
} catch (InterruptedException ex) {
// thrown if someonelse calls notify
}
}
}
If you want to suspend test execution, you need to have someone (i.e. another Thread) execute the following code:
synchronized (monitor) {
suspend = true;
}
To continue again, you would need to execute the following code:
synchronized (monitor) {
monitor.notifyAll();
}
Thats just a very simple solution. There are more sophisticated synchronization styles, but this one should be sufficient.
I have a Function executing Some piece of code Like,
Protected void XXXXfunc()
{
//i register a callback for asynchronous operation below is just an example
// not true to its operation
byte[] buffer = new byte[10];
s.BeginReceive(buffer, 0, 10, SocketFlags.None,
new AsyncCallback(OnMessageReceived), buffer);
}
// Callback function
XXXX callback OnMessageReceived(XXXX)
{
//Something Goes wrong here i throw an exception
throw(exception);
}
Where and how do i catch this exception or where is this exception funneled to be caught.
In the callback, the only place you can catch it.
And yes, that's a very awkward place because that callback runs on a thread you didn't start and runs completely asynchronously from the rest of your code. You have to somehow let the main logic in your program know that something went wrong and that corrective action needs to be taken. Which typically requires raising an event that gets marshaled back to your main thread. At the very least to let the user know that "it didn't work".
This kind of problem is the prime motivation behind the Task<> class in C# version 4 and the async/await keywords added to C# version 5. Which doesn't actually do anything to help the user deal with random failure, it just makes it easier to report.
If an object of type QObject is moved to a thread with QObject::moveToThread, all signals that the object receives are handled inside that thread. However, if a slot is called directly (object->theSlot()) that call will still block. What would be the normal way of executing that call inside the thread and returning control to the calling thread immediately? Hacks with QTimer don't count. Setting up a single purpose connection and deleting it again might count as a solution if all else fails.
You could use QMetaObject::invokeMethod with Qt::ConnectionType set to Qt::QueuedConnection
You can use QFuture<T> QtConcurrent::run ( Function function, ... ) to launch some execution inside a separate thread and then use QFutureWatcher to get the result. You will not need to call movetoThread.
Basically something like :
QFutureWatcher<T>* watch = new QFuture(0);
connect(watch, SIGNAL(finished()), this, SLOT(handleResult()));
QFuture<T> future = QtConcurrent::run( myObj, &QMyObject::theSlot(), args...);
watch.setFuture(future);
....
//slot
private void handleResult(){
if(future->isCancelled())
return;
T mydata = watch->future()->result();
// use your data as you want
}
QtConcurrent::run will schedule the method of this object to be ran in some thread. It is non-blocking. On the other hand, QFuture::result() blocks until there is a result, if the computation is still ongoing. That's why you need the other object to notify when the computation is over using finished(). I cannot think of a better design for your problem in Qt.