Task with infinite cycle - task

I'm new in C#, I've gone to it from Delphi. So may be I do something wrong. My app (windows service) make tasks to control on-off states and count "on" time. I've tried to use Task.Delay(x), but it seems I catch deadlocks...
Main idea make tasks with infinite cycle which performs every x ms. I don't know if I could use the Timer for executing part code in lambda method of task...?
int TagCnt = DataCtrl.TagList.Count;
stopExec = false;
if (TagCnt != 0)
{
tasks = new Task[TagCnt];
for (int i = 0; i <= TagCnt - 1; i++)
{
int TempID = i;
tasks[TempID] = Task.Run(async () => // make threads for parallel read-write tasks // async
{
Random rand = new Random();
TimeSpan delay = TimeSpan.FromMilliseconds(rand.Next(1000, 1500))
try
{
while (!stopExec)
{
cToken.ThrowIfCancellationRequested();
//do basic job here
await Task.Delay(delay, cToken);
}//while end
}
catch (...)
{
...
}
}, cToken);
}

A couple of things went wrong here:
The tasks you're creating are completed instantly, in your case Task.Factory.StartNew returns Task<Task> because of the async lambda. To make it work as expected, unwrap the inner task with Task.Unwrap. Also, remove TaskCreationOptions.LongRunning, you don't need it here:
tasks[TempID] = Task.Factory.StartNew(async () => { ...}).Unwrap();
Alternatively, use Task.Run, it unwraps automatically (more about this):
tasks[TempID] = Task.Run(async () => { ...});
Besides, there's no synchronization context installed on a Windows service thread by default. Thus, the code after await Task.Delay() will be executing on a new pool thread each time, you should be ready for this.
Task.Delay is a bit different from a periodic timer. It will delay the execution. Use Stopwatch to calculate how much to delay for:
// beginning of the loop
stopwatch.Reset();
stopwatch.Start();
// the loop body
// ...
// end of the loop
await Task.Delay(Math.Max(500-Stopwatch.ElapsedMilliseconds, 0));

Related

can I know when a StreamSubscription is cancelled?

is there anything like onCancel for a StreamSubscription?
example:
var subscription = someStream.listen((item) => null);
subscription.cancel(); // does this trigger any event?
I ended up creating a _StreamSubscriptionDelegate that delegates all methods and so I can put some logic when the subscription is cancelled, however, maybe there is an easier solution to it.
If the stream comes from a StreamController, then the controller is notified of the cancel. The listener is expected to keep track of their own subscription, so if one part of the client code needs to know that another part has cancelled the stream, then wrapping the subscription in something which records that you cancelled it, is a perfectly good approach.
Another approach could be to wrap the stream before listening to it:
Stream<T> onCancel<T>(Stream<T> source, void onCancel()) async* {
bool isCancelled = true;
try {
await for (var event in source) {
yield event; // exits if cancelled.
}
isCancelled = false;
} finally {
if (isCancelled) onCancel();
}
}
or
Stream<T> onCancel<T>(Stream<T> source, void onCancel()) {
var sink = StreamController<T>();
sink.onListen = () {
var subscription = source.listen(sink.add, onError: sink.onError, onDone: sink.close);
sink
..onPause = subscription.pause
..onResume = subscription.resume
..onCancel = () {
subscription.cancel();
onCancel();
};
};
return sink.stream;
}

Graph API: What is the correct way to interrupt Pagination

I am using this script to fetch Chats. I need 100 chats maximum but it may happen that a chat do not have 100 messages. How can I handle that case in this script?
I am using Node Package Microsoft Graph Client.
const { Client, PageIterator } = require('#microsoft/microsoft-graph-client');
async getChatList(GroupChatId) {
let messages = [];
let count = 0;
let pauseAfter = 100; // 100 messages limit
let response = await this.graphClient
.api(`/chats/${GroupChatId}/messages`)
.version('beta')
.get();
let callback = (data) => {
messages.push(data);
count++;
return count < pauseAfter;
}
let pageIterator = new PageIterator(this.graphClient, response, callback);
await pageIterator.iterate();
return messages;
}
As I answered on the GitHub issue you opened, the iterator should stop all by itself if it runs out of items to iterate before hitting your "maximum". However, I think you're hitting a bug in the specific API you're using /chats/id/messages.
The problem is that this API is returning a nextLink value in it's response even if there are no next pages. It shouldn't be, and I'm reporting that to the Teams folks. That's causing the pageIterator to try to get the next set of results, which returns 0 items and a nextLink. You're stuck in an infinite loop.
So because of this, using the pageIterator just won't work for this API. You'll need to do the iteration yourself. Here's some TypeScript code to show it:
let keepGoing: Boolean = true;
do
{
// If there are no items in the page, then stop
// iterating.
keepGoing = currentPage.value.length > 0;
// Loop through the current page
currentPage.value.forEach((message) => {
console.log(JSON.stringify(message.id));
});
// If there's a next link follow it
if (keepGoing && !isNullOrUndefined(currentPage["#odata.nextLink"]))
{
currentPage = await client
.api(currentPage["#odata.nextLink"])
.get();
}
} while (keepGoing);
You need to check with a conditional statement if the message has value or not.
The pseudo code is given below:
let callback = (data) => {
if(data != "" || data != null)
{
messages.push(data);
count++;
return count < pauseAfter;
}
else{
return;
}
}

Dart Async Do Something Else Then Wait

I've read several stackoverflow questions, dart documents, and even watched a video on async and await. I haven't found an answer to my question. I would like to call an async method, execute other code, and then wait on the completion of the async task.
Here's an example of what I'm working with. This is my component
Credit credit;
...
Future<Null> getCredit(id) async {
try {
credit = await _creditService.getCredit(id);
}
catch (e) {
errorMessage = e.toString();
}
}
...
void onUpdateCredit(int credit_id) {
getCredit(credit_id);
creditDialogTitle = 'Update Credit';
creditArtistIndex = credit.artist_id;
instrument = credit.instrument;
creditNotes = credit.notes;
creditDialog.open();
}
This code crashes because credit is null when an attempt is made to use it. One way around it is combine the two methods:
Future<Null> onUpdateCredit(id) async {
try {
credit = await _creditService.getCredit(id);
creditDialogTitle = 'Update Credit';
creditArtistIndex = credit.artist_id;
instrument = credit.instrument;
creditNotes = credit.notes;
creditDialog.open();
}
catch (e) {
errorMessage = e.toString();
}
}
Nothing is done is parallel and, if I need the credit some where else in my code, I would have to duplicate the try/catch portion of the method. I could also code it like this:
void onUpdateCredit(int credit_id) {
credit = null;
getCredit(credit_id);
creditDialogTitle = 'Update Credit';
while (credit == null) {//wait a period of time}
creditArtistIndex = credit.artist_id;
instrument = credit.instrument;
creditNotes = credit.notes;
creditDialog.open();
}
In other situations, I do something similar to this in my html with *ngIf="var != null" where var is populated by a future.
Is there a better way than using while (credit == null) ? This example only executes one instruction between the request and the completion so is trivial. I'm sure I'll other situations where I have a lot to do in between. I'm also adding the service method:
Future<Credit> getCredit(int id) async {
try {
String url = "http://catbox.loc/credits/${id.toString()}";
HttpRequest response = await HttpRequest.request(
url, requestHeaders: headers);
Map data = JSON.decode(response.responseText);
final credit = new Credit.fromJson(data);
return credit;
}
catch (e) {
throw _handleError(e);
}
}
Update
Based on #Douglas' answer, this works:
Future<Null> onUpdateCredit(id) async {
Future future = getCredit(id);
creditDialogTitle = 'Update Credit';
await future;
creditArtistIndex = credit.artist_id;
instrument = credit.instrument;
creditNotes = credit.notes;
creditDialog.open();
}
I then eliminated the intervening method.
Future<Null> onUpdateCredit(id) async {
try {
Future<Credit> future = _creditService.getCredit(id);
creditDialogTitle = 'Update Credit';
credit = await future;
creditArtistIndex = credit.artist_id;
instrument = credit.instrument;
creditNotes = credit.notes;
creditDialog.open();
}
catch (e) {
errorMessage = e.toString();
}
}
getCredit(credit_id) does not just kick off an asynchronous call, it also returns a Future object - immediately. Store that object in a local variable, and you can use it later to asynchronously execute additional code when it completes.
There are two ways to use that Future object. The easier and more fluent way requires that you declare onUpdateCredit to be async. Inside an async function, the line await futureObject will cause all code after that line to be executed asynchronously after the Future completes. The complete version of onUpdateCredit using this technique would look like this:
Future<Null> onUpdateCredit(int credit_id) async {
Future future = getCredit(credit_id);
creditDialogTitle = 'Update Credit';
await future;
creditArtistIndex = credit.artist_id;
instrument = credit.instrument;
creditNotes = credit.notes;
creditDialog.open();
}
The other way is to explicitly register the rest of your code as a callback using .then(). That would look like this:
void onUpdateCredit(int credit_id) {
Future future = getCredit(credit_id);
creditDialogTitle = 'Update Credit';
future.then((_) => {
creditArtistIndex = credit.artist_id;
instrument = credit.instrument;
creditNotes = credit.notes;
creditDialog.open();
});
}
Note that in either case, if the exception path occurs in getCredit(id) you will get errors for credit not being set. If you truly want the exception to be swallowed silently, you should have its handler fill in a default value for credit so that code that assumes it completed normally will still work.
Also note that your while loop version would fail - Dart, like JavaScript, is not truly multithreaded, and busy waiting like that will block the event loop forever, preventing the code that would set credit from ever running.
A short summary of how async and await work in general:
Future someFunc(args) async {
...
return value;
}
is equivalent to:
Future someFunc(args) {
return new Future(() => {
...
return value;
}
}
The code inside gets executed on a later iteration of the event loop, and the returned future completes either successfully with value or exceptionally with anything thrown in that code.
Meanwhile this:
try {
value = await someFutureObject;
...more code here...
} catch (e) {
...exception handling here...
}
is equivalent to:
someFutureObject.then((value) => {
...more code here...
}).catchError((e) => {
...exception handling here...
});
The most common use case is someVar = await someAsyncCall();, but you can save the Future itself by omitting await, or you can await on an arbitrary Future object no matter where it comes from.
However - and this is what makes await and async so incredibly convenient - you can have 5 different exit points from the async function interspersed with three await calls (in the same async function) in assorted places inside 13 nested loops, switches, try/catch, and if blocks, and Dart will automatically figure out the necessary tree of callbacks to make it all follow the same code path as if all the calls were synchronous.

How to delete a Dart future when it's no longer needed

This is related to is there any way to cancel a dart Future?
In my case, there are no HTTP, just expensive calculations. I have a table/list which I scroll through. As the elements become visible, I generate futures to show the calculation results. But if I (the end user) scroll quickly, some results will have "scrolled out of view" and will no longer required. This could be a large number, and would seriously delay the return of futures (results) that are to be usefully :-) displayed in currently visible elements. Can something be done about that? cheers, Steve
You could just set a flag which indicates to the delayed code (run from futures) that the result isn't needed anymore.
When the delayed code is called it just returns.
library cancel_future;
import 'dart:async' show Future, Timer;
import 'dart:math' show Random;
typedef void TaskFunction(Task task);
// Container for a task
class Task {
// an assigned task id
final id;
// data to process
int data;
// Indicate to the task function, that it should stop processing
bool isCanceled = false;
// The task function must set this flat to true when all work is done.
bool isFinished = false;
// The task function which processed the data and sets the result.
TaskFunction fn;
// The result set by the task function when it finished processing.
int result;
Task(this.id, this.data, this.fn);
// Start processing the task.
void execute() => fn(this);
}
final rnd = new Random();
void main(List<String> args) {
// create tasks
final tasks = new List<Task>.from(generate());
// start all tasks
tasks.forEach((t) => t.execute());
// after random delay cancel all unfinished tasks
new Future.delayed(new Duration(seconds: rnd.nextInt(10)), () {
tasks.forEach((t) {
if (!t.isFinished) {
t.isCanceled = true;
}
});
}).then((_) {
// check results
int done = 0;
int canceled = 0;
tasks.forEach((t) {
print(
'Task id: ${t.id}; isCanceled: ${t.isCanceled}; isFinished: ${t.isFinished}; data: ${t.data}; result: ${t.result}');
if (t.isFinished) {
done++;
}
if (t.isCanceled) {
canceled++;
}
});
print('Canceled: $canceled.');
print('Done: $done.');
});
}
// geneator for job 100 jobs
Iterable<Task> generate() sync* {
int i = 0;
while (i++ < 100) {
yield new Task(i, rnd.nextInt(100), calc);
}
}
// job function
void calc(Task t) {
// do a bit of work every 100ms to simulate longer processing
new Timer.periodic(new Duration(milliseconds: 100), (timer) {
var result = 0;
// check if jost was canceled and stop processing in case it was.
if (t.isCanceled) {
timer.cancel();
return;
}
// while not finished do a chunk of work
if (result < t.data) {
result++;
} else {
// finished - clean up and store result
t.isFinished = true;
t.result = result;
timer.cancel();
}
});
}

How to wait for 3 seconds in ActionScript 2 or 3?

Is there any way to implement waiting for, say, 3 seconds in ActionScript, but to stay within same function? I have looked setInterval, setTimeOut and similar functions, but what I really need is this:
public function foo(param1, param2, param3) {
//do something here
//wait for 3 seconds
//3 seconds have passed, now do something more
}
In case you wonder why I need this - it is a legal requirement, and no, I can't change it.
Use the Timer to call a function after 3 seconds.
var timer:Timer = new Timer(3000);
timer.addEventListener(TimerEvent.TIMER, callback); // will call callback()
timer.start();
To do this properly, you should create the timer as an instance variable so you can remove the listener and the timer instance when the function is called, to avoid leaks.
class Test {
private var timer:Timer = new Timer(3000);
public function foo(param1:int, param2:int, param3:int):void {
// do something here
timer.addEventListener(TimerEvent.TIMER, fooPartTwo);
timer.start();
}
private function fooPartTwo(event:TimerEvent):void {
timer.removeEventListener(TimerEvent.TIMER, fooPartTwo);
timer = null;
// 3 seconds have passed, now do something more
}
}
You could also use another function inside your foo function and retain scope, so you don't need to pass variables around.
function foo(param1:int, param2:int, param3:int):void {
var x:int = 2; // you can use variables as you would normally
// do something here
var timer:Timer = new Timer(3000);
var afterWaiting:Function = function(event:TimerEvent):void {
timer.removeEventListener(TimerEvent.TIMER, afterWaiting);
timer = null;
// 3 seconds have passed, now do something more
// the scope is retained and you can still refer to the variables you
// used earlier
x += 2;
}
timer.addEventListener(TimerEvent.TIMER, afterWaiting);
timer.start();
}
For AS3 use Radu's answer.
For AS2 use the setInterval function like so:
var timer = setInterval(function, 3000, param1, param2);
function (param1, param2) {
// your function here
clearInterval(timer);
}
You can also use delayedCall, from TweenMax. IMHO, it's the sharpest way to do that if you are familiar to TweenMax family.
TweenMax.delayedCall(1, myFunction, ["param1", 2]);
function myFunction(param1:String, param2:Number):void
{
trace("called myFunction and passed params: " + param1 + ", " + param2);
}
In your case, using a anonymous function:
public function foo(param1, param2, param3) {
//do something here
trace("I gonna wait 3 seconds");
TweenMax.delayedCall(3, function()
{
trace("3 seconds have passed");
});
}
why you are doing some confused ways instead of doing the right way?
there is a method named:"setTimeout()";
setTimeout(myFunction,3000);
myFunction is the function you want to call after the period.and 3000 is the period you want to wait(as miliseconds).
you don't need to set then clear interval, or make a timer with one repeat count or do sth else with more trouble☺.
There is no Sleep in ActionScript. But there are other ways to achieve the same thing without having all your code in a single function and wait within that function a specific amount of time.
You can easily have your code in two functions and call the 2nd one after a specific timeout you set in your 1st function.
THIS IS NOT WITHIN ONE FUNCTION - ANSWERS: "How to wait for X seconds in AS2 & 3"
...without using setInterval or clearInterval.
The answers posted above are much faster and easier to use. I posted this here, just in case...
Sometimes you may not be able to use set/clearInterval or other methods based on development restrictions. Here is a way to make a delay happen without using those methods.
AS2 - If you copy/paste the code below to your timeline, make sure to add two movie clips to the stage, btnTest and btnGlowTest (include like instance names). Make "btnGlowTest" larger, a different color, & behind "btnTest" (to simulate a glow and a button, respectively).
Compile and check the output panel for the trace statements to see how the code is working. Click on btnTest - btnGlowTest will then become visible throughout the duration of the delay, (just for visual representation).
I have an onEnterFrame countdown timer in here as well, (demos stopping/switching timers).
If you want the delay/glow to be longer - increase the glowGameTime number. Change the names to fit your own needs and/or apply the logic differently.
var startTime:Number = 0;
var currentTime:Number = 0;
var mainTime:Number = 5;//"game" time on enter frame
var glowStartTime:Number = 0;
var glowCurrentTime:Number = 0;
var glowGameTime:Number = 1.8;//"delayed" time on press
btnGlowTest._visible = false;
this.onEnterFrame = TimerFunction;
startTime = getTimer();
function TimerFunction()
{
currentTime = getTimer();
var timeLeft:Number = mainTime - ((currentTime - startTime)/1000);
timeLeft = Math.floor(timeLeft);
trace("timeLeft = " + timeLeft);
if(timeLeft <= 0)
{
trace("time's up...3 bucks off");
//...do stuff here
btnGlowTest._visible = false;//just for show
btnTest._visible = false;//just for show
StopTime();
}
}
function glowTimerFunction()
{
glowCurrentTime = getTimer();
var glowTimeLeft:Number = glowGameTime - ((glowCurrentTime - glowStartTime)/1000);
glowTimeLeft = Math.floor(glowTimeLeft);
//trace("glowTimeleft = " + glowTimeLeft);
if(glowTimeLeft <= 0)
{
trace("TIME DELAY COMPLETE!");
//...do stuff here
btnGlowTest._visible = false;//just for show
btnTest._visible = false;//just for show
StopTime();
}
}
btnTest.onPress = function()
{
trace("onPress");
btnGlowTest._visible = true;
StopTime();
GlowTime();
}
function GlowTime()
{
trace("GlowTime Function");
this.onEnterFrame = glowTimerFunction;
glowStartTime = getTimer();
}
function StopTime()
{
trace(">>--StopTime--<<");
delete this.onEnterFrame;
}
AS3 - Below is the code from above setup to run in AS3. There are different ways to accomplish similar results, yet based on the project scope, these are the methods that were used in order to get things functioning properly.
If you copy/paste the code below to your timeline, make sure to add two movie clips to the stage, btnTest and btnGlowTest (include like instance names). Make "btnGlowTest" larger, a different color, & behind "btnTest" (to simulate a glow and a button, respectively).
Compile and check the output panel for the trace statements to see how the code is working. Click on btnTest - btnGlowTest will then become visible throughout the duration of the delay, (just for visual representation).
If you want the delay/glow to be longer - increase the GlowTimer:Timer number, (currently set to 950). Change the names to fit your own needs and/or apply the logic differently.
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
var startTime:Number = 0;
var currentTime:Number = 0;
var gameTime:Number = 4;//"game" time on enter frame
var GlowTimer:Timer = new Timer(950,0);//"delayed" time on press
btnGlowTest.visible = false;
GlowTimer.addEventListener(TimerEvent.TIMER, GlowTimeListener, false, 0, true);
btnTest.addEventListener(MouseEvent.MOUSE_DOWN, btnTestPressed, false, 0, true);
addEventListener(Event.ENTER_FRAME,TimerFunction, false, 0, true);
startTime = getTimer();
function TimerFunction(event:Event)
{
currentTime = getTimer();
var timeLeft:Number = gameTime - ((currentTime - startTime)/1000);
timeLeft = Math.floor(timeLeft);
trace("timeLeft = " + timeLeft);
if(timeLeft <= 0)
{
trace("time's up, 3 bucks off");
StopTime();
}
}
function GlowTimeListener (e:TimerEvent):void
{
trace("TIME DELAY COMPLETE!");
StopTime();
}
function btnTestPressed(e:MouseEvent)
{
trace("PRESSED");
removeEventListener(Event.ENTER_FRAME, TimerFunction);
btnGlowTest.visible = true;
GlowTimer.start();
}
function StopTime()
{
trace(">>--Stop Time--<<");
btnGlowTest.visible = false;//just for show
btnTest.visible = false;//just for show
GlowTimer.stop();
removeEventListener(TimerEvent.TIMER, GlowTimeListener);
removeEventListener(Event.ENTER_FRAME, TimerFunction);
}

Resources