When Completed event is fired after execute Socket.SendAsync? - c#

When Completed event is fired after execute Socket.SendAsync?
I want to know when Completed event is fired after execute Socket.SendAsync.
When Socket.SendAsync process has been done at local endpoint?
Or When Socket.SendAsync process has been done and receive Ack from the remote endpoint?
I'm investigating why Complete event does not infrequently occur after execute Socket.SendAsync.
By the way, I take into consideration the case Socket.SendAsync has been completed synchronously.
bool willRaiseEvent = listenSocket.AcceptAsync(acceptEventArg);
if (!willRaiseEvent){
...
}

Related

Begin reading(dequeue) from MSMQ then stop the dequeue process and then again start in C#

As per the current implementation, C# code adds messages to MSMQ and then after a particular operation is completed, I need to dequeue and start processing them. Following code is used:
_queue.ReceiveCompleted += new ReceiveCompletedEventHandler(RecieveQ_ReceiveCompleted);
_queue.BeginReceive();
However, in between the dequeue process, I would want to stop it and then again start it sometime later, depending on the user input. I came across the EndReceive(IAsyncResult asyncResult) method, but could not implement it correctly.
The BeginReceive() and EndReceive() are not for starting and stopping the queue like turning on and off a tap (or faucet).
In MSMQ, when you call BeginReceive(), a second thread is spawned which waits for a message to enter the queue. When a message arrives, it calls your RecieveQ_ReceiveCompleted event handler.
Inside you event handler, you then call EndReceive() to fetch the item from the queue, and then do your processing. Note that if another item arrives in the queue, it will not be processsed.
If you want to process queue items repeatedly, you have to call BeginReceive() again from within your event handler.
If you want to pause the processing after each item to wait for a signal from the user to process the next item, you will need to signal from the event handler that an item has been processed, and either the event handler or main thread will need to call BeginReceive() again.
Depending on your situation, you might find it easier to use the Receive() method instead of the asynchronous version to better control your order of operations.
References: https://msdn.microsoft.com/en-us/library/43h44x53(v=vs.110).aspx#Anchor_4
In asynchronous processing, you use BeginReceive to raise the ReceiveCompleted event when a message has been removed from the queue.
The MessageQueue can then access the message by calling EndReceive(IAsyncResult).
Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.
Hope this helps

How are async void event handlers called in C#?

If I declare my event handlers as async void, will they be called synchronously or asynchronously by the .NET framework?
I.e., given the following code:
async void myButton_click(object sender, EventArgs e) {
do stuff
await longRunning()
do more stuff
}
Can I be sure that the "do stuff" line will be executed on the GUI thread?
Event handlers will be called synchronously and doesn't wait(await) till the event handler completes, but waits till the event handler returns.
If previous sentence was confusing enough, I'll try to explain it clear. Asynchronous methods completes when all the await points are executed and the end of the method body has reached or any return statement is executed(Ignoring the exception). But asynchronous method returns as soon as you hit the first await statement for the Task which is not yet completed. In other words asynchronous method can return several times but can complete only once.
So now we know when does a asynchronous method completes and returns. Event handler will assume your method has completed as soon as it returns not when it actually completes.
As soon as your event handler reaches first await statement, it will return, if there are more methods attached to same event handler, it will continue executing them without waiting for the asynchronous method to complete.
Yes, do stuff will be executed in UI thread if the UI thread fires the event and yes do more stuff will also be executed in UI thread as long as longRunning().ConfigureAwait(false) isn't called.
They will be invoked just as any other non-async-await method is invoked:
Click(this, EventArgs.Empty);
Because this specific event handler is an async method the call would run synchronously until an await is reached and the rest would be a continuation. That means that do stuff is executed synchronously on the GUI thread. The caller then moves on without the knowledge that the async operation hasn't completed yet.
do more stuff would also be executed on the GUI thread, but for a different reason. The SynchronizationContext in a GUI environment makes sure the continuations would be posted to the single GUI thread, unless you explicitly tell it not to with await longRunning().ConfigureAwait(false)

Wait for an event to finish (threading)

I need to wait for an event to finish before continuing.
Here is my code:
foreach (KeyValuePair<string, Stream> pair in this.XMLCollection)
{
...
this.eventAggregator.GetEvent<LogToApplicationEvent>().Publish(credentials);
//wait
...
}
Before continuing I need to wait for "login" event to execute complately.
I tried using Task.Factory, but it did not work for me, or I cant use it right...
This code is on presenter, but the event updates the main UI.
//publish
public virtual void Publish(TPayload payload)
{
base.InternalPublish(payload);
}
At least two possible solutions:
BackgroundWorker
Use a BackgroundWorker to execute your code, and use the RunWorkerCompleted event to execute the code that is run after completion.
A BackgroundWorker wraps the event based asynchronous pattern into a very easy to use mechanism, complete with progress reporting and cancellation. See this BackgroundWorker tutorial and this SO answer .
Tasks (.NET 4.0 and above)
Use a Task object, and use the ContinueWith method to define the code that needs to be executed after completion of the first task.
Event Aggregator publishing and subscribing event pattern is synchronous. You need not to worry about it.
So, it won't resume until its subscribers are finished executing its delegates.
Assumption - You are using inbuilt Event Aggregator class provided by Microsoft.

Async polling useable for GUI thread

I have read that I can use asynchronous call with polling especially when the caller thread serves the GUI. I cannot see how because:
while(AsyncResult_.IsCompleted==false) //this stops the GUI thread
{
}
So how it come it should be good for this purpose? I needed to update my GUI status bar everytime deamon thread did some progress..
You are correct in your while loop stopping the GUI thread, when doing it like that, you don't want to do that.
If you need to poll, it would be better is to set up a Timer, and check whether the work has completed when the timer fires. The Timer can have a small resolution without problems (100 ms for instance), as long as you dont do much work during each tick.
However, I think you would be even better off by using a callback, so you do not need to poll and get notified as soon as your workload is done.
The point of async polling is that you can do other things in between checking IsCompleted — such as servicing GUI events. You could set a timer, for example, to trigger an event several times per second to check whether your asynchronous operation is finished, and use the normal GUI event loop to service those events together with all the other events your GUI receives. That way, your GUI remains responsive, and shortly after the async operation finishes, your timer event handler will notice it.
I was having the same trouble with an old API exposing BeginExecute() and EndExecute(). BeginExecute() started asynchrounous operation and then went silent until it finished executing to the end. But I was needed to update intermediate state of the execution progress in real-time.
So I came up with the following solution:
var asyncResult = command.BeginExecute();
while (!asyncResult.IsCompleted)
{
if (command.State != OldState)
{
progress.Report(newState);
}
// Key piece in this polling loop.
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
}
command.EndExecute(asyncResult);
At first I have used
await Task.Yield();
But then I found out that in WPF it won't return the control to GUI, because this loop will have higher priority. That is why I switched to this instruction:
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
So now GUI will check and update progress only when it has nothing else to do :)

Block while waiting for event

I have an external COM-object that connects to a server and then fire an event when the server is ready. The connect() call is thus asynchronously.
My code looks (a bit...) like
ManualResetEvent waitConnection;
//This is the event that is triggered when server is ready
public void onConnection_event(bool success)
{
if(success)
waitConnection.Set();
}
private string getItem(string itemName)
{
//MYDBCom is a win32 com if that makes any difference
MYDBCom myDBobject = new MYDBCom();
waitConnection = new ManualResetEvent(false);
myDBobject.connect(); //asynchron call.
//wait until server triggers the onConnection_event
waitConnection.WaitOne();
//server is now ready. Get the data from the server.
return myDBobject.getItem(itemName);
}
The problem is that the event is not triggered - it seems to be blocked while waiting in WaitOne. If I instead of using waitOne use
while(!connected)
{
Sleep(100);
DoEvents();
}
the event is triggered.
Any ideas why WaitOne blocks? Are there any other suggestions how to wait until an event triggers?
//Fredrik
Because the event's message pump is on the same thread as your WaitOne call. The thread is waiting and therefore, is not pumping around your messages.
Update
I should add that using DoEvents() is not usually an advisable solution. There are often better ways of handling the scenario such as having the event fired from a different thread outside of your current thread's message pump so that your current thread doesn't need to be running for the event handler to fire.

Categories

Resources