Consider that I am using thread, which reads data stream from network socket (Windows::Networking::Sockets::StreamSocket) with help of Windows::Storage::Streams::DataReader (m_reader). I need to stop this thread and it waits mostly in LoadAsync. How to correctly cancel LoadAsync method after some timeout?
auto t1 = create_task(m_reader->LoadAsync(sizeof(len)));
t1.wait();
I tried several ways but none worked correctly. Or I can't use DataReader and I must choose some other approach?
Your call t1.wait(); is a blocking call that will throw an exception if the LoadAsync call fails for some reason. In your case, that HRESULT is ERROR_OPERATION_ABORTED, which is pretty much what I would expect ("The I/O operation has been aborted because of either a thread exit or an application request.")
What you could do is create a task cancellation token, attach it to your task, and then fire the token cancellation when desired.
From https://technet.microsoft.com/en-us/office/hh780559:
//Class member:
cancellation_token_source m_fileTaskTokenSource;
// Cancel button event handler:
m_fileTaskTokenSource.cancel();
// task chain
auto getFileTask2 =
create_task(documentsFolder->GetFileAsync(fileName),
m_fileTaskTokenSource.get_token());
Note: calling cancel on the cancellation token will cause the the task to throw a task_canceled exception, so you will need to catch and handle that exception.
Related
I tried to abort the thread and delete a file but the file still gives me the message saying it is used by another process. After aborting the thread it keeps on going through the catch block and I saw a document in Microsoft that says to avoid it from going to end of every catch block if you perform reset.Abort , the abort process will be cancelled, that means the file will still have a process that is using it. Is there a way I can abort my thread before closing the application and delete a file?
if(!task.IsCompleted)
{
Thread t1 = Thread.CurrentThread;
if (Thread.CurrentThread.Name == null)
{
Thread.CurrentThread.Name = "Action_Thread";
}
try
{
t1.Abort("Aborted");
}
catch(ThreadAbortException ex)
{
Debug.WriteLine(ex.Message);
}
finally
{
Debug.WriteLine("Thread now being aborted");
}
File.Delete("somefile.txt");
Most platforms only automatically close file handles when processes exit, not individual threads, so you have to close or unlock the file (or its handle) before aborting the thread.
How this would be done, and whether it can be done automatically on thread abort or requires the abort logic to explicitly call the close operation, depends on which platform or language environment you are using.
I'm using NodeJS to manage a Twilio Taskrouter workflow. My goal is to have a task assigned to an Idle worker in the main queue identified with queueSid, unless one of the following is true:
No workers in the queue are set to Idle
Reservations for the task have already been rejected by every worker in the queue
In these cases, the task should fall through to the next queue identified with automaticQueueSid. Here is how I construct the JSON for the workflow (it includes a filter such that an inbound call from an agent should not generate an outbound call to that same agent):
configurationJSON(){
var config={
"task_routing":{
"filters":[
{
"filter_friendly_name":"don't call self",
"expression":"1==1",
"targets":[
{
"queue":queueSid,
"expression":"(task.caller!=worker.contact_uri) and (worker.sid NOT IN task.rejectedWorkers)",
"skip_if": "workers.available == 0"
},
{
"queue":automaticQueueSid
}
]
}
],
"default_filter":{
"queue":queueSid
}
}
}
return config;
}
This results in no reservation being created after the task reaches the queue. My event logger shows that the following events have occurred:
workflow.target-matched
workflow.entered
task.created
That's as far as it gets and just hangs there. When I replace the line
"expression":"(task.caller!=worker.contact_uri) and (worker.sid NOT IN task.rejectedWorkers)"
with
"expression":"(task.caller!=worker.contact_uri)
Then the reservation is correctly created for the next available worker, or sent to automaticQueueSid if no workers are available when the call comes in, so I guess the skip_if is working correctly. So maybe there is something wrong with how I wrote the target expression?
I tried working around this by setting a worker to unavailable once they reject a reservation, as follows:
clientWorkspace
.workers(parameters.workerSid)
.reservations(parameters.reservationSid)
.update({
reservationStatus:'rejected'
})
.then(reservation=>{
//this function sets the worker's Activity to Offline
var updateResult=worker.updateWorkerFromSid(parameters.workerSid,process.env.TWILIO_OFFLINE_SID);
})
.catch(err=>console.log("/agent_rejects: error rejecting reservation: "+err));
But what seems to be happening is that as soon as the reservation is rejected, before worker.updateWorkerFromSid() is called, Taskrouter has already generated a new reservation and assigned it to that same worker, and my Activity update fails with the following error:
Error: Worker [workerSid] cannot have its activity updated while it has 1 pending reservations.
Eventually, it seems that the worker is naturally set to Offline and the task does time out and get moved into the next queue, as shown by the following events/descriptions:
worker.activity.update
Worker [friendly name] updated to Offline Activity
reservation.timeout
Reservation [sid] timed out
task-queue.moved
Task [sid] moved out of TaskQueue [friendly name]
task-queue.timeout
Task [sid] timed out of TaskQueue [friendly name]
After this point the task is moved into the next queue automaticQueueSid to be handled by available workers registered with that queue. I'm not sure why a timeout is being used, as I haven't included one in my workflow configuration.
I'm stumped--how can I get the task to successfully move to the next queue upon the last worker's reservation rejection?
UPDATE: although #philnash's answer helped me correctly handle the worker.sid NOT IN task.rejectedWorkers issue, I ultimately ended up implementing this feature using the RejectPendingReservations parameter when updating the worker's availability.
Twilio developer evangelist here.
rejectedWorkers is not an attribute that is automatically handled by TaskRouter. You reference this answer by my colleague Megan in which she says:
For example, you could update TaskAttributes to have a rejected worker SID list, and then in the workflow say that worker.sid NOT IN task.rejectedWorkerSids.
So, in order to filter by a rejectedWorkers attribute you need to maintain one yourself, by updating the task before you reject the reservation.
Let me know if that helps at all.
It would be neat if you could chain process.on('exit') calls like so
process.on('exit', function firstHandler(err,code,cb){ //this signature is fictitious for this example only
if(condition){
cb(null); // this would call the next process.on('exit') listener
}
});
process.on('exit', function secondHandler(err,code,cb){
//we really exit this time
});
is this functionality possible somehow? I know this goes against the way event emitters / listeners work, but the reason I ask the question is because I want to prevent an exit if there is a certain condition and then reinvoke process.exit() once the condition is met.
It already works that way. By default, EventEmitters add event listeners when the on() method is called (default maximum is 10 listeners though you can change that). Since the exit event is implemente as a regular EventEmitter, you can add more than one listener by calling on() multiple times:
process.on('exit',function(){console.log('will exit')});
process.on('exit',function(){console.log('really, I will quit')});
process.on('exit',function(){console.log('DEAD')});
Output:
will exit
really, I will quit
DEAD
Note that the listeners will be called in the sequence they were added. See the documentation of Events for more info: https://nodejs.org/api/events.html
You can't cancel an exit. From the doc:
Emitted when the process is about to exit. There is no way to prevent the exiting of the event loop at this point, and once all 'exit' listeners have finished running the process will exit.
Once the "exit" event is emitted, you cannot prevent the node.js process from terminating.
However, if you listen for the "beforeExit" event, shown here:
https://nodejs.org/api/process.html
You can prevent the process / event loop from terminating by adding calls.
The Azure Service Bus supports a built-in retry mechanism which makes an abandoned message immediately visible for another read attempt. I'm trying to use this mechanism to handle some transient errors, but the message is made available immediately after being abandoned.
What I would like to do is make the message invisible for a period of time after it is abandoned, preferably based on an exponentially incrementing policy.
I've tried to set the ScheduledEnqueueTimeUtc property when abandoning the message, but it doesn't seem to have an effect:
var messagingFactory = MessagingFactory.CreateFromConnectionString(...);
var receiver = messagingFactory.CreateMessageReceiver("test-queue");
receiver.OnMessageAsync(async brokeredMessage =>
{
await brokeredMessage.AbandonAsync(
new Dictionary<string, object>
{
{ "ScheduledEnqueueTimeUtc", DateTime.UtcNow.AddSeconds(30) }
});
}
});
I've considered not abandoning the message at all and just letting the lock expire, but this would require having some way to influence how the MessageReceiver specifies the lock duration on a message, and I can't find anything in the API to let me change this value. In addition, it wouldn't be possible to read the delivery count of the message (and therefore make a decision for how long to wait for the next retry) until after the lock is already required.
Can the retry policy in the Message Bus be influenced in some way, or can a delay be artificially introduced in some other way?
Careful here because I think you are confusing the retry feature with the automatic Complete/Abandon mechanism for the OnMessage event-driven message handling. The built in retry mechanism comes into play when a call to the Service Bus fails. For example, if you call to set a message as complete and that fails, then the retry mechanism would kick in. If you are processing a message an exception occurs in your own code that will NOT trigger a retry through the retry feature. Your question doesn't get explicit on if the error is from your code or when attempting to contact the service bus.
If you are indeed after modifying the retry policy that occurs when an error occurs attempting to communicate with the service bus you can modify the RetryPolicy that is set on the MessageReciver itself. There is an RetryExponitial which is used by default, as well as an abstract RetryPolicy you can create your own from.
What I think you are after is more control over what happens when you get an exception doing your processing, and you want to push off working on that message. There are a few options:
When you create your message handler you can set up OnMessageOptions. One of the properties is "AutoComplete". By default this is set to true, which means as soon as processing for the message is completed the Complete method is called automatically. If an exception occurs then abandon is automatically called, which is what you are seeing. By setting the AutoComplete to false you required to call Complete on your own from within the message handler. Failing to do so will cause the message lock to eventually run out, which is one of the behaviors you are looking for.
So, you could write your handler so that if an exception occurs during your processing you simply do not call Complete. The message would then remain on the queue until it's lock runs out and then would become available again. The standard dead lettering mechanism applies and after x number of tries it will be put into the deadletter queue automatically.
A caution of handling this way is that any type of exception will be treated this way. You really need to think about what types of exceptions are doing this and if you really want to push off processing or not. For example, if you are calling a third party system during your processing and it gives you an exception you know is transient, great. If, however, it gives you an error that you know will be a big problem then you may decide to do something else in the system besides just bailing on the message.
You could also look at the "Defer" method. This method actually will then not allow that message to be processed off the queue unless it is specifically pulled by its sequence number. You're code would have to remember the sequence number value and pull it. This isn't quite what you described though.
Another option is you can move away from the OnMessage, Event-driven style of processing messages. While this is very helpful you don't get a lot of control over things. Instead hook up your own processing loop and handle the abandon/complete on your own. You'll also need to deal some of the threading/concurrent call management that the OnMessage pattern gives you. This can be more work but you have the ultimate in flexibility.
Finally, I believe the reason the call you made to AbandonAsync passing the properties you wanted to modify didn't work is that those properties are referring to Metadata properties on the method, not standard properties on BrokeredMessage.
I actually asked this same question last year (implementation aside) with the three approaches I could think of looking at the API. #ClemensVasters, who works on the SB team, responded that using Defer with some kind of re-receive is really the only way to control this precisely.
You can read my comment to his answer for a specific approach to doing it where I suggest using a secondary queue to store messages that indicate which primary messages have been deferred and need to be re-received from the main queue. Then you can control how long you wait by setting the ScheduledEnqueueTimeUtc on those secondary messages to control exactly how long you wait before you retry.
I ran into a similar issue where our order picking system is legacy and goes into maintenance mode each night.
Using the ideas in this article(https://markheath.net/post/defer-processing-azure-service-bus-message) I created a custom property to track how many times a message has been resubmitted and manually dead lettering the message after 10 tries. If the message is under 10 retries it clones the message increments the custom property and sets the en queue of the new message.
using Microsoft.Azure.ServiceBus;
public PickQueue()
{
queueClient = new QueueClient(QUEUE_CONN_STRING, QUEUE_NAME);
}
public async Task QueueMessageAsync(int OrderId)
{
string body = JsonConvert.SerializeObject(OrderId);
var message = new Message(Encoding.UTF8.GetBytes(body));
await queueClient.SendAsync(message);
}
public async Task ReQueueMessageAsync(Message message, DateTime utcEnqueueTime)
{
int resubmitCount = (int)(message.UserProperties["ResubmitCount"] ?? 0) + 1;
if (resubmitCount > 10)
{
await queueClient.DeadLetterAsync(message.SystemProperties.LockToken);
}
else
{
Message clone = message.Clone();
clone.UserProperties["ResubmitCount"] = ++resubmitCount;
await queueClient.ScheduleMessageAsync(message, utcEnqueueTime);
}
}
This question asks how to implement exponential backoff in Azure Functions. If you do not want to use the built-in RetryPolicy (only available when autoComplete = false), here's the solution I've been using:
public static async Task ExceptionHandler(IMessageSession MessageSession, string LockToken, int DeliveryCount)
{
if (DeliveryCount < Globals.MaxDeliveryCount)
{
var DelaySeconds = Math.Pow(Globals.ExponentialBackoff, DeliveryCount);
await Task.Delay(TimeSpan.FromSeconds(DelaySeconds));
await MessageSession.AbandonAsync(LockToken);
}
else
{
await MessageSession.DeadLetterAsync(LockToken);
}
}
In my project I have created some network calls to the servlets in separate Thread where before that thread starts I show a spinner as wait progress. Until that network Thread finishes the waitprogress is displayed on to the screen and when I receive response from the server I have to explicitly call progress bar's dispose() method to dispose that progress bar. So, This is bit complicated whenever I make calls establishing GPRS connection while network strength goes down there I found sometimes it takes about 2-3 minutes to throw an IO Exception or receive response from server where I dispose waitprogress, show error message and proceed. I dont add any cancel command to waitprogress as network calls are made using separate thread so disposing waitprogress will allow user to make another call where the user is needed to wait until he gets response.
The above scenario is complicated because the user will not be waiting for this long to get response. There must be some way that whenever I call network Thread and show progress bar the user should be able to cancel all the operations including network thread, go back to previous state and make another call if there is no or poor connectivity.
Here, I am using Lwuit.
In NetworkManager class you can add this function and actived at from your class
only if lwuit is at open code in your application , you can add this function:
public void killAll() {
for (int i = 0; i < pending.size(); i++) {
((ConnectionRequest) pending.elementAt(i)).kill();
}
pending.removeAllElements();
for (int i = 0; i < networkThreads.length; i++) {
networkThreads[i].currentRequest.kill();
}
}
after or before this you need call dispose() method.