In task list item added event i have two methods as below
method1() // execution time : 3 seconds
method2() // execution time : 2 seconds
here before completing the method1() executing it automatically moving to the method2() and its started executing. somehow i can understand this is because of the async event. How to resolve this issue?
If its because of the async event you can make the after event synchronous (SP 2010 and up).
$receiver.Synchronization = "Synchronous"
$receiver.Update()
Check this for modifying event receivers with PowerShell.
Related
In the example on dart.dev the Future prints the message after the main function was done.
Why might the Future work after the main function was done? At first glance, after the completion of the main function, the entire work of the program is expected to be completed (and the Future must be cancelled).
The example code:
Future<void> fetchUserOrder() {
// Imagine that this function is fetching user info from another service or database.
return Future.delayed(Duration(seconds: 2), () => print('Large Latte'));
}
void main() {
fetchUserOrder();
print('Fetching user order...');
}
The program prints
Fetching user order...
Large Latte
I've expected just the following
Fetching user order...
This has to do with the nature of futures and asynchronous programming. Behind the scenes, Dart manages something called the asynchronous queue. When you initiate a future (either manually like you did with Future.delayed or implicitly by calling a method marked async, that function's execution goes into the queue whenever its execution gets deferred. Every cycle when Dart's main thread is idle, it checks the futures in the queue to see if any of them are no longer blocked, and if so, it resumes their execution.
A Dart program will not terminate while futures are in the queue. It will wait for all of them to either complete or error out.
The first question is when the event loop starts ?
I read in a site that it's start after the main method
but why when we try something like this
main()async {
Future(()=>print('future1'));
await Future(()=>print('future2'));
print('end of main');
}
//the output is :
//future1
//future2
//end of main
in this example the event loop start when we use the await keyword and
after the event loop reaches the future2 it's paused ?
or i am wrong :(
The second question is how the events is added to event queue
if it's FIFO why in this example the future 2 is completed before
future 1
main(){
Future.delayed(Duration(seconds:5) , ()=>print('future1'));
Future.delayed(Duration(seconds:2) , ()=>print('future2'));
}
The event loop run when there is nothing else running (e.g. main method is done, you are waiting for some future to complete).
Your example makes sense because the first line puts an event on event queue so now the first item in the queue is "print('future1')". In the next line, you are putting another event on the queue which calls "print('future2')" and now you await for this event to be done.
Since your main method is not waiting for something then the event loop is going to be executed. Since the first event on the queue was "print('future1')" then this is going to be executed first. But since the main method is still waiting for the future "print('future2')" to be complete then the event loop takes another event to be executed which are going to be "print('future2')".
Since this event was the one the main method was waiting for (and there is no more event on the event queue) then main() are going to run the last call "print('end of main')".
In your next example, you think that Future and Future.delayed are the same which it is not. With Future.delayed there are not going any event in the event queue before. Instead, there are running a thread outside the VM which knows when the next timer should trigger which ends up putting an event on the queue. So the event is only being put on the event queue when the timer has been expired (and therefore, the future2 are going to be executed first).
I have a Command that executes a service call. In the result handler, I am doing some logic based off the result data. If the logic meets specific criteria, I am displaying a confirmation popup. If the user clicks the continue button in the confirmation popup, I have a method that gets called, which dispatches a Parsley event. That Parsley event is not being caught. However, if I dispatch the Parsley event from inside the result method, it is being caught. Any idea why the event is not being caught when dispatching it from outside the result method?
For example...
[MessageDispatcher]
[Bindable]
public var dispatcher:Function;
I execute some service call from inside the command:
public function execute(event:SomeEvent):AsyncToken
{
return service.callService(event.type, false);
}
I now have a result handler like this:
public function result(data:Object):void
{
if (add some logic here based off data)
AlertHelper.showContinueQuestion(onSelection, "Are you sure you want to continue?");
}
If the user clicks the Continue button on the confirmation popup, it calls the onSelection method:
private function onSelection():void
{
dispatcher(new SomeEvent(SomeEvent.UPLOAD));
}
That Parsley event, SomeEvent, is not being caught. However, if I dispatch that event after the if statement, it is being caught and works fine. Any idea why it is not being caught when dispatched from outside of the result handler? I tried in other commands too, and it does the same thing.
Found this on the Spicefactory site, works as designed. I ended up updating a flag in the Model, versus dispatching an event. I then have a BindSetter listening for changes to that flag in the model. When the flag is set to true, the Parsley event is dispatched.
Command Object Lifecycle
Apart from grouping the executing method and the result handlers the DynamicCommand also introduces a special kind of lifecycle management for command objects. The creation of the object does not happen until a matching message is dispatched. It then becomes a container managed object just for the duration of the command execution. It will immediately be removed from the Context after the result or error handler have been invoked. But during its lifetime, it is a fully managed object, can have its dependencies injected, or even take part in messaging during the command execution. But that would be a rather rare case, most common usage scenario is probably the command object just receiving all the dependencies it needs to execute the command.
I have a Windows Phone 8 app that utilizes SQLite.
I have a problem where some async SQLite operations hang indefinitely (presumably because they are awaited?)
Here is one such operation:
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("myDatabase");
var query = conn.Table<MyTable>().Where(x => x.Name == "name");
var result = await query.ToListAsync();
foreach (var item in result)
{
// breakpoint in the code here is never reached
}
This is in an async method which returns a Task< string>
This method is called early from the main page code. The main page never actually builds, as the app is hanging on this method (the screen just says "Loading..." indefinitely until I stop)
I'm guessing that further up your call stack (e.g., in your main page code), you are calling Result on a Task<T>. This will deadlock your program. I explain this in detail in my Best Practices in Asynchronous Programming article and my Don't Block on Async Code blog post.
To summarize: when you await an uncompleted Task, by default the current context is captured and used to restore the remainder of the async method after the Task completes. In your case, the captured context is a UI context, which only runs on a specified thread (the UI thread).
So, your main page code calls your async method which awaits the ToListAsync operation (capturing the UI context). Your async code returns an uncompleted Task to your main page code which calls Result on it. Result will (synchronously) block until the Task completes. When the ToListAsync operation completes, it attempts to execute the rest of your async method within the captured (UI) context. But the UI thread is busy; it's blocked waiting for that Task to complete. Thus, deadlock.
I am making some probes with async CTP but I don't get a good result, because the GUI is blocked.
I have an WPF application with a button and a textBox for a log. Then I have this code:
private async void btnAsync01_Click(object sender, RoutedEventArgs e)
{
UpdateTxtLog("Enter in Button Async01: " + System.DateTime.Now);
await metodo01Async();
UpdateTxtLog("Exit button Async01: " + System.DateTime.Now);
}
private async Task slowMethodAsync()
{
UpdateTxtLog("Enter in slowMethod: " + System.DateTime.Now);
Thread.Sleep(5000);
UpdateTxtLog("Exit slowMethod: " + System.DateTime.Now);
}
If am not wrong, set a method with "sync" (click event in this case), it let the method use the await, to return the point to execution to the method which call the actual method, then the execution return to the GUI.
So in the GUI,I click the button, then in the click event await to the slowMethod, how I use await with the slowMethod the control should be returned to the GUI, and then the GUI should not be blocked. However, the GUI is blocked and the txtLog not show any information until slowMethod finish.
Is this because slowMethod is executed in the same thread than the GUI? If I am wrong, with async normally use the same thread than the method which call the await method, but I think that the reason of the async avoid this.
How can I simulate an slowMethod without thread.Sleep? Perhaps this is the problem, because in slowMethod I sleep the thread, and the thread of slowMethod is the same than the GUI.
This makes me think that is always recommended execute in other thread the code of the async methods? If this is correct, which is the sense to use async if also I need to use task for not blocking the main thread?
When to use async and when to use tasks?
For this probes, I am following the examples in this web: http://www.codeproject.com/Articles/127291/C-5-0-vNext-New-Asynchronous-Pattern
In this example, it's used client.DownloadStringTaskAsync as slowMethod, but in my case, instead of using a WebClient, I use a dummy method, with a sleep to simulate a slowMethod. I think that is the unique difference.
Thanks.
Daimroc.
Simulate waits using await TaskEx.Delay(5000), which executes an asynchronous sleep/delay.
You may also want to read up some more on async/await. There are several good Channel9 videos; Stephen Toub, Eric Lippert, and many other Microsoft bloggers have excellent overviews. Jon Skeet's "eduasync" blog series is also good for really going deep. I've written up an async intro on my own blog, as have many others.
Here's how async and await really work, in a nutshell:
The async keyword only enables the await keyword. That is all. It does not run the method on a background thread.
await only acts asynchronously if its "awaiter" is not completed.
So in your case, btnAsync01_Click and slowMethodAsync both run on the UI thread. slowMethodAsync will run synchronously (executing Thread.Sleep), and then return to btnAsync01_Click, which awaits the already-completed task. Since the task is already completed, btnAsync01_Click just continues executing without yielding to the UI message loop.
If you replace Thread.Sleep with await TaskEx.Delay, then btnAsync01_Click will start running on the UI thread, and will call slowMethodAsync (also running on the UI thread). When slowMethodAsync awaits the delay (which is not completed), it will return an incomplete task to btnAsync01_Click. btnAsync01_Click will await that task (which is not completed), and will return to the UI loop.
When the delay expires, it will complete, and slowMethodAsync will resume (on the UI thread). When slowMethodAsync completes, its returned task will complete, and btnAsync01_Click will resume (on the UI thread).