FAQ Database Discussion Community


generating templates with grunt - looking for a task

javascript,node.js,templates,gruntjs,task
I've got an HTML file with following content: <html> <body> <span>{{ secret }}</span> </body> </html> I'm looking for a grunt task that could take this source file, take a map of values: grunt.initConfig({ myTask: { myTarget: { src: ... dest: ... values: { secret: 'ABC' } } } }) and...

Why is Task not co-variant?

c#,task,covariance
class ResultBase {} class Result : ResultBase {} Task<ResultBase> GetResult() { return Task.FromResult(new Result()); } The compiler tells me that it cannot implicitly convert Task<Result> to Task<ResultBase>. Can someone explain why this is? I would have expected co-variance to enable me to write the code in this way....

Java job execution multithreaded with executorservice?

java,multithreading,task,executorservice
How to i implement such a function ? I have a dynamic queue which gets filled at unknown times with runnables, which have to be executed. The ExecutorService should only start a limited amount of threads, when the maximum thread size is reached, it should stop executing more threads, until...

Gulp task apply uglify if file in pipe is javascript

javascript,pipe,task,gulp
I want to check if the file in the pipe is .js or not (it could be .map, .html, ...). And if so, uglifying it before copying it in the correct path. ʕ •́؈•̀) I've try something like this (which not working): gulpfile.js gulp.src(current + '/**/*', {base: current}) .pipe($.tap(function (file)...

Parallel.Invoke works slowly

c#,parallel-processing,task
I wrote code Methode #1 and Methode #2 for compare performance. Methode #1 use construnction for, and Methode #2 using Parallel.Invoke. In second scenario works very slowly. I can't understand why it was happening ? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Collections.Concurrent; using...

gulp watch doesn't watch

javascript,node.js,task,gulp
Following is my gulpfile.js. There are a couple of more tasks in it and all are working fine - but the last task, watch doesn't. I've tried every possible combination of paths and files and what so ever, but still I don't have luck. I've read many answers on this...

Creating async version of a generic method

c#,task,generic-method
I have this generic method for Deserializing a type public static T Deserialize<T>(string xmlString) { if (string.IsNullOrWhiteSpace(xmlString)) return default(T); using (MemoryStream memStream = new MemoryStream(Encoding.Unicode.GetBytes(xmlString))) { memStream.Position = 0; System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); return (T)serializer.Deserialize(memStream); } } Now I wish to make an async version which I tried like...

Wait for an event to fire using tasks in .net 4

c#,winforms,.net-4.0,task
I have function A that calls function B from an external class that I cannot modify. Function B fires an event when completed on which I subscribed the doSomeStuff function. I only want to finish Function A when doSomeStuff is finished. I can only use .Net 4, so no use...

Innosetup task Page edit

checkbox,task,inno-setup
I want to edit the task page in inno-setup and make checkbox for: Install Visual C++ I have Tried- [Tasks] Name: desktopicon; Description: {cm:CreateDesktopIcon}; GroupDescription: {cm:AdditionalIcons} Name: vcredist_x64; Description: Install Visual C++; Flags: unchecked [Code] procedure CurStepChanged(CurStep: TSetupStep); begin if CurStep = ssPostInstall then begin var ResultCode: Integer; begin if...

TaskScheduler with limited concurrency blocks itself

c#,multithreading,task
I am trying to use the following custom TaskScheduler to limit concurrent web requests: https://msdn.microsoft.com/en-us/library/ee789351%28v=vs.110%29.aspx I'm using it like this: const int CONCURRENCY_LEVEL = 2; static void Main() { TaskFactory factory = new TaskFactory(new LimitedConcurrencyLevelTaskScheduler(CONCURRENCY_LEVEL)); Task.WaitAll(new[] { factory.StartNew(() => SomeAction("first")), factory.StartNew(() => SomeAction("second")) }); Console.WriteLine("All tasks ended"); Console.Read(); } static...

Get statistic of executed tasks in C#

c#,task-parallel-library,task
I have following simple code: var tasks = statements.Select(statement => _session.ExecuteAsync(statement)); var result = Task.WhenAll(tasks).Result; [...] How can I calculate min, max, avg, etc. of all executed tasks? The task class doesn't have property like "executedMilliseconds"...

Why invoking the event cancels the task?

c#,events,task
I have a Task that checks the time of a device per second: public void checkTimeStart() { CancellationTokenSource cTokenSource = new CancellationTokenSource(); CancellationToken ct = cTokenSource.Token; Task task = Task.Factory.StartNew(async () => { ct.ThrowIfCancellationRequested(); while (!ct.IsCancellationRequested) { await Task.Delay(1000); string time = getTime(); TimeUpdateEvent.Invoke(this, new TimeUpdateEventArgs(time)); } }, cTokenSource.Token); }...

Why is the task is not cancelled when I call CancellationTokenSource's Cancel method in async method?

c#,asynchronous,task,cancellationtokensource,cancellation-token
I created a small wrapper around CancellationToken and CancellationTokenSource. The problem I have is that the CancelAsync method of CancellationHelper doesn't work as expected. I'm experiencing the problem with the ItShouldThrowAExceptionButStallsInstead method. To cancel the running task, it calls await coordinator.CancelAsync();, but the task is not cancelled actually and doesn't...

TaskCanceledException with ContinueWith

c#,.net,task
I've been trying to figure out why I'm getting a TaskCanceledException for a bit of async code that has recently started misbehaving. I've reduced my issue down to a small code snippet that has me scratching my head: static void Main(string[] args) { RunTest(); } private static void RunTest() {...

How to set multiple pidfile in sidekiq.yml file?

ruby-on-rails,queue,task,jobs,sidekiq
From the official wiki page of sidekiq I found: https://github.com/mperham/sidekiq/wiki/Advanced-Options --- :concurrency: 5 :pidfile: tmp/pids/sidekiq.pid staging: :concurrency: 10 production: :concurrency: 20 :queues: - default - [myqueue, 2] Now I want to create multiple tasks using the same sidekiq.yml file. But use different pid name, such as: /tmp/pids/task1.pid /tmp/pids/task2.pid How to...

Unable to set “Run whether user is logged on or not”

sql,powershell,task,scheduler
I have a Powershell script to add a new schedule task. It's used to launch a PS1 file which includes some SQL querying on both local SQL box and remote SQL boxes. If this script creates the schedule, I have to make one change manually for it to work: I...

FX Task, returning a value always returns null

java,javafx,task
I am trying to return a String from a FX Task. Expected output: true,testABC. Real output: true,null. The call to the task: public static void main(String[] args) { ExecutorService pool = Executors.newCachedThreadPool(); Future<String> my_String = (Future<String>) pool.submit(new my_task()); try { Thread.sleep(500); System.out.println(my_String.isDone()); System.out.println(my_String.get());//gettings the String from the future } catch...

How to express Task dependencies in sbt 13

scala,dependencies,sbt,task
I am trying to express dependencies between two tasks in sbt 13.5. What I want to do is execute TaskB before TaskA will be executed. So I am trying to force the two Tasks to execute sequentially instead of parallel. In other words TaskA should wait for TaskB to finish....

Alternate ways to cancel async task

vb.net,multithreading,task
I am trying to find the best way to do this and none of my attempts thus far has worked. Looking for some additional input. I have a sub that needs to be executed in the background and is something like this Sub Start_Work() 'Step 1 Sleep(1000) 'Step 2 Sleep(2000)...

Access two entries of one task at the same time by different tasks

multithreading,task,ada
I need to acces two different entries of one task by two different tasks. Looks like my knowledge about Ada is not enough to perform this, i also spent a lot of time searching for solution but with no effects. I tried using protected type as a manager but it...

PeriodicTask with Django + Celery

python,django,task,celery
I am trying to do a Periodic task in my project but I can't make it work. In my dev I execute celery like this: python manage.py celery worker -l info But when I try: celery -B -l info or python manage.py celery -B -l info I get a Connection...

Send a success signal when the group of tasks in celery is finished

django,signals,task,group,celery
So i have a basic configuration django 1.6 + celery 3.1. Say i have an example task: @app.task def add(x, y): time.sleep(6) return {'result':x + y} And a function that groups and returns job id def nested_add(x,y): grouped_task = group(add.s(x,y) for i in range(0,2)) job = result_array.apply_async() job.save() return job.id...

How to pass parameters in gulp dependencies

parameters,dependencies,task,gulp
I'd like to prepare a different versions of a software by passing a special parameters in gulp task. I've created tasks for css, js, etc. and made one to run then all: gulp.task('compile', ['css', 'twig', 'js', ....]); How to pass a parameter which will be passed also to the subtasks?...

Create outlook task from shared inbox

vba,outlook,task
I need to create outlook task from shared inbox. So far when below code runs, task is created with owner of shared inbox as I want, but when saved I get "You must be in a public folder to change the owner field of a task" error and owner is...

Task.Run with Parameter(s)?

c#,lambda,task-parallel-library,task
I'm working on a multi-tasking network project and I'm new on Threading.Tasks. I implemented a simple Task.Factory.StartNew() and I wonder how can I do it with Task.Run()? Here is the basic code: Task.Factory.StartNew(new Action<object>( (x) => { // Do something with 'x' }), rawData); I looked into System.Threading.Tasks.Task in Object...

What are the ContinueWith default values

c#,.net,multithreading,task-parallel-library,task
What values use ContinueWith(Action<Task> continuationAction) for CancellationToken, TaskContinuationOptions and TaskScheduler and where can I find this in the official documentation?

Visual studio 2013 not hitting breakpoints in a referenced project in debug

c#,debugging,visual-studio-2013,task,breakpoints
I have two solutions, one is my main app and the other is a plugin. I am editing the plugin for my app so I have added the plugins project to my apps solution and referenced it instead of the .dll I am having problems with the breakpoints in the...

Wpf UI bahaviour strangeness in ContinueWith, when Task itself works too fast

c#,wpf,task
Code to emulate bug. XAML: </Grid.RowDefinitions> <TextBlock Grid.Row="0" Grid.Column="0" Margin="5,5,5,0" FontSize="14" HorizontalAlignment="Right" Text="User:"> </TextBlock> <TextBox Grid.Row="0" Grid.Column="1" Margin="5,5,5,0" Name="_txtLogin" Text="{Binding Login}"/> <Button Grid.Row="1" Grid.Column="1" Content="Ok" Width="100" VerticalAlignment="Center" HorizontalAlignment="Center" Click="AutentificateClick" Padding="0,2,0,2" IsDefault="True" Name="_btnOk" /> </Grid> Code: private Boolean...

Moving data from one BlockingCollection to the other

task,c#-5.0,producer-consumer
I have a code, that copies integers to buffer1, then from buffer1 to buffer2 and then consumes all data from buffer2. It processes 1000 values in 15 seconds, which is a lot of time compared to size of input. When I remove the " Task.Delay(1).Wait() " from the second task...

jBPM 6.2.0 send recurring Task reminder after 1 day time interval if the task is not complete

events,timer,signals,task,jbpm
I am new to jBPM. I am working on jBPM version 6.2.0. I want to perform following tasks. Send reminder email to user / group. Remind the user again after 1 business day if the task is not yet complete. Continue to send reminder everyday untill the task is done....

Cleaning up CallContext in TPL

c#,asynchronous,task-parallel-library,async-await,task
Depending on whether I'm using async/await based code or TPL based code, I'm getting two different behaviors regarding the clean-up of logical CallContext. I can set and clear logical CallContext exactly as I expect if I use the following async/await code: class Program { static async Task DoSomething() { CallContext.LogicalSetData("hello",...

Task await fails

c#,asynchronous,async-await,signalr,task
I am starting a HubConnection. First I get a new Instance of HubConnection, afterwards I create a new IHubProxy with Name = "fileHub" so far so good. My problem is located at (or in) the awaitable Function ContinueWith, I try to start the Connection, and write to the console wheater...

Using Task.Factory.StartNew for tasks queue

c#,multithreading,task
I want to use a task queue for background stuff in my C# application. From reading stuff on the web, I understood that calling Task.Factory.StartNew will queue a task on the TaskScheduler queue. When I do this, I get a compiler warning because I'm not awaiting the result of Task.Factory.StartNew....

Use of if clause in OpenMP

synchronization,task,openmp
Can't figure out the use of the if (0) clause in the following code as there also exists the #pragma omp single clause. Any ideas? ...

Is the following async enabled code liable to cause a deadlock

c#,asynchronous,task-parallel-library,async-await,task
public async Task<Foo> Execute(int id) { var parameters = new { id}; using (var con = new SqlConnection(this.connectionString)) { await con.OpenAsync(); return await con.QueryAsync<foo>( "dbo.uspGetMeFoo", parameters, commandType: CommandType.StoredProcedure, commandTimeout: int.Parse(ConfigurationManager.AppSettings["SqlCommandTimeout"])) .ContinueWith(task => task.Result.FirstOrDefault()); } } This method is awaited on in a calling class, where - some time after...

WebClient Timeout takes longer than expected (Using: Rx, Try Catch, Task)

c#,timeout,task,webclient,system.reactive
Problem: I inherited WebClient in ExtendedWebClient where I override the WebRequest's timeout property in the GetWebRequest method. If I set it to 100ms, or even 20ms, it always takes up to more than 30 seconds at least. Sometimes it seems to not get through at all. Also, when the service...

Benefits of using async and await keywords

c#,.net,multithreading,asynchronous,task
I'm new in the use of asynchronous methods in C#. I have read that these keywords async and await help to make the program more responsive by asynchronizing some methods. I have this snippet : First Way public static void Main() { Console.WriteLine("Hello!! welcome to task application"); Console.ReadKey(); Task<string> ourtask...

NodeJS how to wait multi tasks complete

node.js,task
I want to spider some links and after all tasks done,i want to do something else. How to track tasks done is hard for me.Hope someone can help. here is my code: var urlList=[]; //Ready file lines lineReader.eachLine('url.txt', function(line) { console.log('url is :'+line); urlList.push(line); }).then(function(){//After Read,begin to proceed each line...

What is the point of .NET 4.6's Task.CompletedTask?

c#,task,.net-4.6
This blog post mentions the new Task APIs, including a new Task.CompletedTask property introduced in .NET 4.6. Why was this added? How is this better than, say, Task.FromResult(whatever)?...

Error handling using delegates

c#,error-handling,task-parallel-library,async-await,task
I have a common method that I'm using to handle a specific error that may come back from a number of functions: protected async Task<T> RunMyMethod<T>(Func<T> method) { try { var returnValue = await Task.Run<T>(method); return returnValue; } catch (MyCustomException) { // Force a clean shutdown of the software ShutdownApplication();...

Excel Interop: Creating instance with Task.Run results in exception System.EntryPointNotFoundException

c#,task,excel-interop
Here is my minimal example producing the problem: using System.Runtime.InteropServices; using System.Threading.Tasks; using Excel = Microsoft.Office.Interop.Excel; class Program { static void Main(string[] args) { Task.Run(() => { Excel.Application app = new Excel.Application(); if (app != null) { app.Quit(); Marshal.FinalReleaseComObject(app); app = null; } }); } } This results in the...

Task vs Barrier

c#,task,barrier
So my problem is as follows: I have a list of items to process and I'd like to process the items in parallel then commit the processed items. The barrier class in C# will allow me to do this - I can run threads in parallel to process the list...

What the difference between using .NET tasks with method and action?

c#,.net,action,task
Method: static void HelloWorld() { Console.WriteLine(“Hello, world!”); } What the difference between Task t1 = new Task(HelloWorld); and Task t2 = new Task(new Action(HelloWorld)); ...

What happens to non-awaited tasks in WCF?

c#,multithreading,wcf,asynchronous,task
Let's say you have this console application: static void Main(string[] args) { var httpClient = new HttpClient() { BaseAddress = new Uri("http://www.timesofmalta.com") }; var responseTask = httpClient.GetAsync("/"); } Since the task is not awaited, the program reaches its end, finds no other foreground threads executing, and exits before any response...

How do I terminate a task upon object deletion? c#

c#,garbage-collection,task
Consider the following class class Melody { public Melody() { Task.Factory.StartNew(()=>play_melody_in_loop()); } } play_melody_in_loop plays melody in loop and never completes. Instances of Melody can be collected by GC when they go out of scope. If it happens, I want to stop the playback. Can I avoid implementing IDisposable?...

cancel async task if running

c#,task,cancellation
I have the following method called on several occasions (e.g onkeyup of textbox) which asynchronously filters items in listbox. private async void filterCats(string category,bool deselect) { List<Category> tempList = new List<Category>(); //Wait for categories var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; //HERE,CANCEL TASK IF ALREADY RUNNING tempList= await...

Calling a Func From a Task

c#,task,func
I am writing a custom reporting tool that allows the users to possibly create some very broad queries. I wanted to add a timeout to this so if the user creates something that will end up running quite long, the entire system won't stall. I came up with this: public...

C# get object from asyncron task

c#,task
i just startet thread programming in c#. And I realy dont know if this is the right community to ask questions like that. If not, im sorry. I have two functions, start() and status(). In start() I create an new task like: start() { for each(dir => ListOfAllDirs) { new...

Create an exception-converting dynamic proxy that works with tasks

c#,task,castle-dynamicproxy
Problem I'm somehow running in circles... I try to create an interface proxy with target using Castle Dynamic Proxy. The proxy should Return the return value of the invocation if no exception is thrown (i.e. do nothing). Throw new InterceptedException if the invocation throws an InvalidOperationException. Throw e if the...

In C#; what is the most efficent way to check for changes from a background thread?

c#,multithreading,task
I create a thread for each of my network communications and they add to a list responses whenever they hear back from a client. I'm starting up the task below at execution to see if any communications come in. It displays the most recent one on screen. Task task =...

How to use javaFX Task in my case - Not duplicate

java,user-interface,javafx,task
I know there are answers for my questions but I did not understand the problem in my code. Why I get : java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4 I'm trying to add text from a Task to a Text flow using a method in the controller class,...

Adding Eclipse Mylyn Subtasks disabled

eclipse,task,mylyn
I've taken the plunge and am using Mylyn finally, and I don't know why I didn't do this sooner, it's amazing. That said there are a few features I haven't been able to get working, one specifically is "Sub-tasks". When I right click existing task -> new -> subtask, the...

Gulp task runs much faster without 'return' statement - why is that?

build,return,task,gulp
Gulp task formed like this (without return) runs much faster: gulp.task('less', function () { gulp.src('./less/**/*.less') .pipe(less()) .pipe(gulp.dest('./destination')); }); than the same one with return: gulp.task('less', function () { return gulp.src('./less/**/*.less') .pipe(less()) .pipe(gulp.dest('./destination')); }); So, my question is what does Gulp task is supposed to return? Why is it so much...

Is Timer or Task good for tasks with long idle time

c#,timer,task
I have a set of projects that need to run only once at specific times every day. I was thinking to run each project as a webservice and use Timer or Task.Delay to schedule the work, but is timer/task good for scheduling work with long idle time? Here is my...

How to avoid over-nesting exceptions when using Task continuations

c#,exception,task
In some part of my code I have this: task.Exception.InnerException.InnerException.Message Which seems wrong to me. Is it normal? The origin of this is when I do a ContinueWith to a task, but in the ContinueWith y throw again the exception if it wasn't the success case, like this: t.ContinueWith(task =>...

Why Task.WhenAll(taskList) doesn't work?

c#,asynchronous,async-await,task
If the task in foreach isn't async, and make ping.Send instead of ping.SendPingAsync then Task.WhenAll(taskList) will work. List<Task> taskList = new List<Task>(); foreach (var host in hostArray) { var aHost = host; Task task = new Task(async ()=> { Ping ping = new Ping(); PingResult pingRes = new PingResult {...

About pxHigherPriorityTaskWoken

task,freertos
In the description of xSemaphoreGiveFromISR at http://www.freertos.org/a00124.html is written: "From FreeRTOS V7.3.0 pxHigherPriorityTaskWoken is an optional parameter and can be set to NULL." The question is: If the parameter is NULL and there is higher priority task affected by the semaphore, will it automatically be switched after ISR - without...

Multi Threading, Task.Run Error 'The call is ambiguous between the following methods or properties' [duplicate]

c#,multithreading,task,ambiguous
This question already has an answer here: Compiler Ambiguous invocation error - anonymous method and method group with Func<> or Action 4 answers When I try to build project the following error message is displayed. The call is ambiguous between the following methods or properties: 'System.Threading.Tasks.Task.Run(System.Action)' and 'System.Threading.Tasks.Task.Run(System.Func)' How...

Finish a task in c# application

c#,multithreading,asynchronous,task
I'm beginner in the use of task in C#, I have this method : public async void GetAnimateur(Action<List<fsign_fiche_signaletique>, Exception> callback) { try { Task<List<fsign_fiche_signaletique>> data = (Task<List<fsign_fiche_signaletique>>)Task.Run( () => { DataEntities _db = new DataEntities(); _db.Configuration.LazyLoadingEnabled = false; var dpcs = _db.fsign_fiche_signaletique.ToList(); return new List<fsign_fiche_signaletique>(dpcs); }); var result = await...

MVC controller can't execute Async method

c#,asp.net-mvc-4,async-await,task
I have a very basic MVC controller with one action: public class HomeController : Controller { public ActionResult Index() { OpenConnection().Wait(); return View(); } private async Task OpenConnection() { var synchronizationContext = SynchronizationContext.Current; Debug.Assert(synchronizationContext != null); using ( var connection = new SqlConnection( @"Data Source=(localdb)\ProjectsV12;Initial Catalog=Database1;Integrated Security=True;")) { await connection.OpenAsync();...

C# in Async Task change Label Text

c#,user-interface,asynchronous,label,task
The following Code does not change the Text and stops executing the Task private void button1_Click(object sender, EventArgs e) { label1.Text = "Test"; Task.Run(() => MyAsyncMethod()); } public async Task MyAsyncMethod() { label1.Text = ""; //everything from here on will not be executed } would be really handy if you...

Conversion errors when returning a generic task from a method

c#,azure,async-await,task
I've created a method to return a task from a query on an Azure mobile service. But when I set the return type for the method, ie Task I get these errors pointing to the return part of the method: I tried to remedy this by using a generic ILIst...

.Net Task class - please explain

c#,.net,asynchronous,async-await,task
Can someone please explain why the public async Task DoStuff() method below can still work without returning anything? It doesn't say void, so I assumed the return type would have to be Task. When I remove the async and await keywords from the DoStuff() method, the compiler gives me a...

ForEachAsyc with Result

c#,linq,task-parallel-library,task
I'm trying to change Stephen Toub's ForEachAsync<T> extension method into an extension which returns a result... Stephen's extension: public static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body) { return Task.WhenAll( from partition in Partitioner.Create(source).GetPartitions(dop) select Task.Run(async delegate { using (partition) while (partition.MoveNext()) await body(partition.Current); })); } My approach...

Is there any way to disable a windows.form.timer inside a Task?

c#,timer,thread-safety,task
Is there any way to disable a windows.form.timer inside a task? here is an example code that I have. private void timer1_Tick(object sender, EventArgs e) { Task.Factory.StartNew( () => {runTask();} ); } private void runTask() { //Process here.... timer1.enabled = false; MessageBox.Show(timer1.Enabled.ToString()); } When I run the program the value...

How to calculate the frequency of word in Zipf's law?

collections,task,frequency,words,ir
There are 4 different words a, b, c, d in a collection where their frequency order is a > b > c > d. The total number of tokens in this collection is 1500. Using Zipf's law, what are the frequencies of the four words? Is there any formula for...

Task that has asynchronous IO operation

c#,asynchronous,task-parallel-library,async-await,task
(I am still in early stage of learning async-await and Task Parallel Library.) I was asked to add some functionality to our existing project: send out email notification when system gets important data. // part of API; called by other parts of the program public override void PrivateSignal(IEventInformation ev) {...

Optimum use of Concurrent Collections with Threads Vs. Tasks

c#,multithreading,collections,concurrency,task
I've been reading this article on MSDN about C# Concurrent Collections. It talks about the optimum threading to use for particular scenarios to get the most benefit out of the collections e.g: ConcurrentQueue performs best when one dedicated thread is queuing and one dedicated thread is de-queuing. If you do...

Summing up decimals returned within task

vb.net,task,wait
I'm trying to run through a list of 1-X items and process them in Tasks in order to speed up completion of processing (they make web requests that can sometimes take a short while to finish). I'm trying to sum up a decimal that is returned when the processing is...

c# Simple TASK Cancel

c#,task-parallel-library,task
I'm tying stop thread by nothing works. I was trying on 100 ways. What is wrong ? It is irritating (I have to write some text here because stackoverflow.com don't allow me to send this post)(I have to write some text here because stackoverflow.com don't allow me to send this...

IActionFilter returning a new Task never returns

c#,asp.net-web-api,async-await,task,action-filter
In an ASP.NET Web API project, I have an action filter which checks for model state errors and returns the Bad Request status code if there are any. It looks like this: public class ValidationFilter : IActionFilter { public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext context, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) { if(!actionContext.ModelState.IsValid) { return...

Use Ant task from salesforce-ant.jar in gradle script

ant,gradle,task,build.gradle,build.xml
I have the following task definition in build.xml <taskdef resource="com/salesforce/antlib.xml" uri="antlib:com.salesforce"> <classpath> <pathelement location="${env.ANT_HOME}/lib/ant-salesforce.jar" /> </classpath> </taskdef> I want to import its in gradle script. I used following task definition in build.gradle // ant-salesforce.jar in buil folder repositories { flatDir { dirs '.' } } configurations { antSf } dependencies...

C# async doesn't await

c#,json,asynchronous,async-await,task
The app I'm working on is supposed to retrieve a json string with the http client after which it gets deserialised and used in the app. Everything works, except for the await functionality. I'm doing something wrong and I can't seem to figure out what. How can I make sure...

TPL async await - does the async Task have to chain up the call stack?

c#,asynchronous,task-parallel-library,async-await,task
My understanding is that the following is bad practice since it blocks the thread: Task t = Task.Run(() => MyMethod()); t.Wait(); Whilst the following does not block the thread: await MyMethod(); However, to use await, one has to use the async keyword in the method signature, and return a Task...

Why second thread with ContinueWith option is not waiting for first thread's end?

c#,multithreading,task
Why second thead started by line var finalTask = parent.ContinueWith( .. ) is not waiting for first thread's end? This is printout proving that the new thread is not waiting for the first one's end: Starting main thread 1 Starting ContinueWith thread 2 0 0 0 Ending ContinueWith thread 2...

External Function Call Blocks UI thread

c#,multithreading,.net-4.0,task
I am working on an application that talks to a motion controller over ethernet. To connect to the controller I use a library provided by the supplier, to connect you create an instance of the controller than then tell it to connect, this has the chance to block for a...

Communcate with object inside a Task

c#,multithreading,task
I want to know how or even if its required in my case to communicate with an object running inside a Task. I have a collection of processes, which are generic objects that perform some long running monitoring and calculating: private IEnumerable<IService> _services; Since they are based on a common...

How can I test a method with a Task return type?

c#,unit-testing,async-await,task
I am trying to test a method whose signature is of the form public async Task<List<int>> MethodToBeTested() I have written a unit test as follows [TestMethod] public async Task MethodToBeTestedSuccess() { Task<List<int>> results = await MethodToBeTested() ...... } If the method's return type had been a generic List of integers...

How do I kill a task in batch?

windows,batch-file,task
I am having problems with the taskkill in batch, I am trying to kill a vbscript that is in sleep for an x amount of seconds. So basically I want to kill this task: http://i.imgur.com/nNVf1Fh.png But I somehow seem to get it wrong, I have no clue what part of...

Understanding Threads and Synchronization with .NET and WPF

c#,wpf,asynchronous,task
I've been programming in C++ for years and then moved to .NET. Everything much easier to understand so far, but I still struggle with synchronization things (in theory). I remember seeing here on Stackoverflow that running a Task won't actually create a new thread! That got me really confused. How...

Celery limit number of specific task in queue

python,queue,task,celery,worker
I'm using Celery 3.1.x with 2 tasks. The first task (TaskOne) is enqueued when Celery starts up through the celeryd_after_setup signal: @celeryd_after_setup.connect def celeryd_after_setup(*args, **kwargs): TaskOne().apply_async(countdown=5) When TaskOne is run, it does some calculations and then enqueues TaskTwo. Imagine the following workflow: I start celery, thus the signal is fired...

Should we use ConfigureAwait(false) in libraries that call async callbacks?

c#,async-await,task-parallel-library,task,synchronizationcontext
There are lots of guidelines for when to use ConfigureAwait(false), when using await/async in C#. It seems the general recommendation is to use ConfigureAwait(false) in library code, as it rarely depends on the synchronization context. However, assume we are writing some very generic utility code, which takes a function as...

Sleep Task on Form load not working

c#,winforms,parallel-processing,async-await,task
I am using the following code to apply a delay in my form load method before it becomes visible (after a splash screen is shown). I have defined my form load as async: private async void MainForm_Load(object sender, EventArgs e) And this is my delay function at the end of...

Understanding different variants of declaring a task in Gradle

android-studio,gradle,task,android-gradle,build.gradle
There are two different variants of declaring a task in Gradle. 1. task myTask() {} 2. task task3 << {} To test how they behave, I´ve created a sample android project apply plugin: 'com.android.application' android { compileSdkVersion 22 buildToolsVersion "21.1.2" defaultConfig { applicationId "com.android.gradletest" minSdkVersion 15 targetSdkVersion 22 versionCode 1...

Intent-filter - Open NEW application, not embedded one

android,android-intent,task,intentfilter
I don't know if it's really understandable. When i'm clicking on a llink in a mail, I can open this link with my application and that's perfeclty what I want. <intent-filter> <data android:scheme="https" android:host="xxx.xxx.com"/> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.BROWSABLE"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> BUT When i'm opening my application like that, and...

How to call async task from parent class?

c#,asp.net,task
Today I need your help to debug my code... Indeed, I need to use the Task object to make API calls but it don't work. My RestClient to execute my get / post / put requests: public class RestClient { public HttpClient HttpClient { get; set; } public RestClient() {...

Access Alfresco Workflows I've started in JavaScript

javascript,workflow,task,alfresco,alfresco-share
I'm trying to create a report about the workflows (Adhoc task) that a person is/was involved in and I'm having trouble with accessing the workflows that the person has started and are currently in progress. I am using JavaScript API and using workflow Root Scope object. With this I can...

background thread using Task.Run

c#,.net,multithreading,task-parallel-library,task
Do you see any pitfalls or issues when spawning off two separate tasks for an Oracle db query and Active Directory query and then waiting for both. Below is a very basic stripped down example. Essentially we have an employee object that gets created from pieces of info from AD...

Not getting the hang of TASKs and WAIT in C#

c#,asynchronous,async-await,task
I have a stack of calls to a web api that need to be called asynchronously. I have never used the aysnc. I have created a simple test console program, along the lines of : class Program { static void Main(string[] args) { ClassOne xx = new ClassOne(); var v1...

Multi-Threading/Task making minimal difference, how to speed up process

vb.net,multithreading,task
I feel like I am doing something wrong here and not sure what, because I am not noticing a big difference with respect to multi-threading. I have a 'Convert_Data' function that does a fair amount of processing of data. I tested it using 1 Task and saw that it was...

What is the proper way to detect parent Task cancellation?

c#,c#-4.0,task,semaphore
I am developing a proof of concept app that factors a list of numbers using tasks and a semaphore, currently I have a List of Tasks,List<Task>, that take a FactorNumberClass and then calculate the factors of the specific number within the FactorNumberClass this currently works correctly. With each Task T,...

Fork() to performe different processes

c,unix,fork,task,children
I'm trying to use the multiple fork() calls to create several children with different task I found a code on Multiple child process Which is really close for what I want , yet I couldn't fully understand it pid_t firstChild, secondChild; firstChild = fork(); if(firstChild != 0) { // In...

Transform a sync method to async with C#

c#,asynchronous,async-await,task
I have two methods. I want to wait the first one and some times wait the other (but not all the time). So I think I should use a task and await it when I want to wait, and not await it when I don't want to wait. EDIT :...

Proper way to handle a group of asynchronous calls in parallel

c#,parallel-processing,async-await,task
I have a console app that calls a web api and gets a list of services. It then loops through and makes calls to each service. I have the following: static int Main(string[] args) { ... Task.WaitAll(Process()); } private static async Task BeginProcess() { using(HttpClientHandler handler = new HttpClientHandler()) {...

Update Int32 in Task c#

c#,multithreading,thread-safety,task-parallel-library,task
is there any way to increment a value of an int inside a task? or is this a correct syntax in incrementing an int in task? sample code: public int erCount = 9; static void Main(string[] args){ Task.Factory.StartNew(() => { ...do some task if(errorfound) erCount++; }); Task.Wait(); Console.Writeline(erCount.toString()); } I...

CancellationTokenSource vs. volatile boolean

c#,task,volatile,cancellationtokensource
Are there any benefits for using a CancellationTokenSource over a volatile boolean field for signalling a Task to finish?

Task.Run( () MethodName()) and await Task.Run(async () => MethodName())

c#,parallel-processing,task
I am trying to understand if using await Task.Run(async () => MethodName()) in MVC 5 gives the benefits of freeing up the thread of a long running IO operation, while continuing with other code tasks in Parallel. I know that simply using "await MethodName()" will free up the thread, but...

UI unresposive on a long-time for loop

c#,winforms,task
I have a WinForm Application that reads data from an excel file using Spreadsheetlight, There is a method that reads the information then do some calculation an then I create a new excel File. The problem is that this file has about 100,000 records and I have a label in...

Executing more than 1000 HTTP request tasks fails

c#,concurrency,task-parallel-library,httprequest,task
I'm trying to load test an API. I'm executing a tasks at the same time, each executing an HTTP request. I use Task.WhenAll(mytasks) for waiting for all tasks to be finished. The requests look as follows: using (var response = await client.SendAsync(request).ConfigureAwait(false)) { using (var jsonResponse = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) {...

Update GUI From Task.Factory

c#,asp.net,task
I am using ASP.Net and what i want to achieve is that i have a service that i call, before calling the service i manipulate some UI controls and after the service is completed i manipulate the UI controls again. Problem is that the UI controls values are never changed...