Click here to Skip to main content
15,893,594 members
Everything / Task

Task

Task

Great Reads

by Federico Alterio
Elegant replacement for awaiting a limited set of tasks
by Alon Lek
Running tasks in parallel while taking into account the dependencies between them
by honey the codewitch
Explore adapting Socket's async model to a task based one and adding some awaitable socket operations to your projects
by M. van der Corput
Simple task based spinner for a console application

Latest Articles

by Federico Alterio
Elegant replacement for awaiting a limited set of tasks
by honey the codewitch
Use TaskCompletionSource to turn an event or callback based model into a Task based one
by honey the codewitch
Explore adapting Socket's async model to a task based one and adding some awaitable socket operations to your projects
by honey the codewitch
Leveraging some less well known areas of the .NET Task framework to schedule tasks to execute on your own conditions.

All Articles

Sort by Score

Task 

4 Sep 2023 by Federico Alterio
Elegant replacement for awaiting a limited set of tasks
10 Jun 2017 by Alon Lek
Running tasks in parallel while taking into account the dependencies between them
18 Mar 2016 by Richard Deeming
Task.Delay will create a new Task (technically, a DelayPromise) and a Timer:Task.Delay | Reference Source[^]However, in your example, it will do this once per second. It won't "whiz round" creating new objects in a tight loop, because the await ensures that the rest of the method doesn't...
9 May 2012 by Sergey Alexandrovich Kryukov
I hope you won't be able to kill them all, it cannot make any sense, anyway, but why would I care if you want to screw up your system? You will reboot it (because you hardly will be able to work at all if you kill some of the critically important applications).Whatever. Those are not...
19 Mar 2014 by Sergey Alexandrovich Kryukov
Let me give you a really short introduction.You can use threads in a way abstracted from the CPU cores. And the OS associates cores with threads using its own. In almost all cases, this is the very best option. I would not recommend touching process and thread affinity at all. The cases when...
29 Sep 2020 by OriginalGriff
Use a BackgroundWorker - it can report back to the UI thread as necessary: private void FrmMain_Shown(object sender, EventArgs e) { BackgroundWorker work = new BackgroundWorker(); ...
22 Apr 2013 by Sergey Alexandrovich Kryukov
You can get this information is you use System.Diagnostics.PerformanceCounter:http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter.aspx[^].You can use this introductory CodeProject article to see how to do things: An Introduction To Performance...
22 Apr 2013 by Zoltán Zörgő
Actually all the information you got so far is correct:- Task manager is just a tool to display data. It is not collecting anything- In the background of task manager (and others like this) are system level tools, like WMI, as Mike Meinz highlighted.- And you can access them easily also...
15 Mar 2016 by RickZeeland
Here is a good article by Stephen Cleary: Async/Await - Best Practices in Asynchronous Programming[^]But I'm afraid he says what you don't want to hear:Quote:As you convert synchronous code to asynchronous code, you’ll find that it works best if asynchronous code calls and is called by...
23 Jul 2020 by honey the codewitch
Explore adapting Socket's async model to a task based one and adding some awaitable socket operations to your projects
9 Nov 2021 by Richard Deeming
Task.WhenAny will return the first task which completed. You can use that to remove it from the list. while (!gotSuccess && _tasks.Count != 0) { Task completedTask = await Task.WhenAny(_tasks); _tasks.Remove(completedTask); ...
23 Jun 2013 by cigwork
Have you considered using the Workflow library? If you have and don't think it's suitable then have a look at something I hacked together something a while ago. It might serve as a jumping off point for you.ΝUnit Inspired Task Runner[^]As outlined the code builds fixed order sequences...
13 Mar 2016 by M. van der Corput
Simple task based spinner for a console application
7 Dec 2016 by RedDk
Suspend, by "stopping", then when done doing what you need to do, restart ... or not!
23 Jan 2018 by OriginalGriff
Threading is complicated, because it's non-deterministic when exactly thread runs, and how long they run for. The "problem" is that each thread requires a core to run on: so the more cores your processor has, the more thread it can actually run at the same time. If you have two cores, then only...
1 Oct 2019 by Richard Deeming
Simple - just remove the async keyword: protected virtual Task MyFunction() { return Task.FromResult(string.Empty); } If your task completes synchronously most of the time, you might want to consider using ValueTask instead. Understanding the Whys, Whats, and Whens of ValueTask |...
4 Aug 2023 by Sonhospa
Hi all, I'm afraid it's my (messed up) syntax that results in a repeated task running syncroniously instead of using multiple tasks (i.e. the 'Debug.WriteLine' message reports Thread 5 all the time). Would someone who has the relevant...
5 Aug 2023 by Graeme_Grant
There are no asynchronous operations. You need to use asynchronous File methods. Alternatively, wrap your call to TestForLTO_async in a Task.Run in the Select Linq method. UPDATE I have knocked up an example of how to do it with the...
10 May 2012 by Sergey Alexandrovich Kryukov
[Answering the follow-up question, from the comment to the original question:]MR. AngelMendez wrote:How about closing any windows that are behind my full screen window?Of course you do it but why? It won't solve your problem.Anyway, you can use Windows API to get HWND of a desktop and...
18 Nov 2012 by Sergey Alexandrovich Kryukov
Your collection type should be thread-safe. It is not, this is not a problem, but you should make all calls you use thread safe, by simply wrapping each of them in the lock statement on the same lock object: lock(someLockObject) firstsortedlist.Add(item.Key, item.Value);// where...
12 Dec 2012 by Dominic Abraham
HiIn task scheduler, you can specify the command line arguments. Go to task scheduler -> double click on your task --> Go to 'Actions' --> Select your action --> 'Edit' --> 'Add Argumenets'. This you can read in your application start up.
12 Dec 2012 by Dominic Abraham
HiI think you can read the arguments from your Task Scheduler in your application main method.For Example.[STAThread] static void Main(string[] yourArgs) { yourArgs[0] // "your first argument"; yourArgs[1] // "your second argument"; }
13 Jun 2013 by CPallini
I would:Parse the file (it is simple, read a line at time and use String.Split to retrieve its different field values).Then either:Store the parsed info inside a database and use such database for searching, etc...orMaintain such data in main memory (if feasible) and perform the...
30 Jun 2021 by Member 10052408
Hi All,I have multiple tasks and i need to run them on specific multiple cores or processors simultaneously. For Example, if i have two different tasks or just one task but will run it twice i want to run these two tasks on specific cores or processors simultaneously like task1 will...
2 Jul 2014 by Kornfeld Eliyahu Peter
You have to push all your task into an array of tasks upon creation. At the point where you want to wait to them add call to Task.WaitAll[^] method...
11 Aug 2014 by Dave Kreskowiak
Try removing the "usings" from the Tasks. I've never put a task in a using statement.
22 Sep 2014 by Sergey Alexandrovich Kryukov
zhshqzyc wrote:@SA, My understanding for Invoke or BeginInvoke is only for UI? Can we use them for long running back end process?You are right. If you want to delegate some execution to some other thread, this is a totally different issue — you have to implement such behavior yourself.My...
7 Nov 2014 by Tomas Takac
It matters when you register your cancellation action. You are doing some work you want to be able to cancel. So it makes no sense to register the cancellation action after you already finished your work, correct? CancellationToken merely gives you the signal that cancellation was requested, you...
21 Jan 2015 by Michael Breeden
I put together a multi-threaded application and seem to have made a mistake... quite fascinating and all, but not good.I was hoping someone had a suggestion or you may say (like I thought "that should not be a problem")I'll try to make this as simple and short as possible, but still show the...
17 Aug 2015 by Thomas Nielsen - getCore
A task supports for instance the property IsCompleted and a Status containing a TaskStatus value of which several can be completed i.e. completed with or without fault.https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx[^]The Task.WaitAll takes an array of...
19 Mar 2016 by Patrick Skelton
Hi,I thought I was beginning to understand the new async/await keywords. Then I had cause to write something like the code below, similar to an extremely slow game loop, which simply runs continuously until a flag changes value. This is a much-shortened version of the code:public...
24 Mar 2016 by Richard Deeming
The default timeout for async actions is 45 seconds. To override that, add the AsyncTimeout attribute[^] to your action:[AsyncTimeout(60000)]public async Task YourAction(){ ...}If you want your action to never time out, you can use the NoAsyncTimeout attribute[^],...
6 Sep 2016 by Bernhard Hiller
Returning a simple result asynchronously is a pain.Following code compiles:public async Task, bool>> GetQuestionOptions(List studsList){ var tmp = new Tuple, bool>(new List(), true); return await Task.FromResult(tmp);}The magic is in...
9 May 2018 by George Swan
You need to check within your method to see if cancellation has been requested. Here is a snippet from a ViewModel to show the sort of pattern you need. private CancellationTokenSource cts; //called from a 'start' button click private async void OnStartAsync(object arg) { ...
25 May 2018 by ChandraRam
The absolute same program, with same logged in user, runs correctly when invoked directly, but behaves differently when run as a scheduled task. What am I missing? Any suggestions welcome, thank you in advance. Edited to add program description: The program is kind of like a console app - it...
31 Jul 2018 by Vincent Maverick Durano
Are you using version 3.x of Quartz? If so then take a look at this short discussion on how to run it on .NET Core: https://stackoverflow.com/questions/41821568/how-to-start-quartz-in-asp-net-core The idea is to call your method for starting the scheduler before calling host.Run();
22 Jul 2019 by OriginalGriff
As far as I'm aware, you can't do Application.Restart except on the main thread - because part of the Restart operation involves closing the forms and that will terminate any sub-threads that the app has opened. When the thread closes, the sub-thread terminates, and it doesn't get to the code...
3 Sep 2020 by Richard Deeming
Try using a Tuple for the local state: Parallel.ForEach(files, Function() (Length := 0L, Count := 0L), Function(f As FileInfo, loopState As ParallelLoopState, index As Long, accumulator As (Length As Long, Count As Long)) If...
16 Jan 2021 by RickZeeland
Take a look at: Parallel.For Method (System.Threading.Tasks) | Microsoft Docs[^] And: Batch.Parallel[^]
28 Oct 2021 by Patrick Skelton
When I lived in the C++ world, I found the subject of threading intuitive. Here in C#, I find I get completely lost, because there seems to be so many ways to do things. Task is probably the best choice most of the time but these are now so...
28 Oct 2021 by Richard Deeming
How about something like this? public class AudioPlayer : IDisposable { private CancellationTokenSource _tokenSource; private void CancelFade(CancellationTokenSource newTokenSource) { var oldTokenSource =...
9 Nov 2021 by Patrick Skelton
I am playing in a new Console application in an attempt to finally get a proper understanding of Task and its various methods. Below is my test program and the output from it. My question is: why do I get the 'Ending task' messages after the...
8 Nov 2021 by OriginalGriff
Because you are thinking in a linear way, instead of a multithreaded manner: each thread - each of your tasks and the main thread that started them - is an independant "runnable entity" which will execute on a core as one becomes available as and...
9 Nov 2021 by Richard Deeming
Quote: private static Task CreateNewTask( int index ) => new Task( async () => { Console.WriteLine( $"Starting task {index}." ); await Task.Delay( TaskDelays[ index ] ); Console.WriteLine( $"Ending task {index}." ); }); This is...
4 Feb 2022 by OriginalGriff
Your "small sample" of code will not work. You can't add an infinite amount of data to a Text box, Rich or not: each time you try, you create a new string which is longer than the last, and cause a Paint event to be queued on the TextBox - which...
23 Jul 2023 by Graeme_Grant
Quote: Something seems to be wrong This is like saying "My car won't start". We're like "did he turn the key, what happened?". You need to be specific. When you ran the code did you get a thread exception error? That would be my first guess as...
20 Jan 2012 by mikewhitney
I am writing a program that shows a drive/directory tree which then populates a files list (ListView). If the user tries to select a network drive that isn't available, the program stops responding to user input for about 25 seconds. I think the program hangs on a call to...
20 Jan 2012 by Nathan Stiles
This uses threading to perform the task off the UI thread then calls back to the UI in a thread safe way.using System;using System.Windows.Forms;using System.Threading;namespace ReflectRefCount{ public partial class Form1 : Form { private delegate void...
8 Mar 2012 by platolgy
In my application, I schedule a job fire by every second. I paused it for 5 seconds and then resumed it. The system execute the job 5 times right now! That not good !So , how can I make the system execute it for once or do nothing when I resume the job?
8 Mar 2012 by TorstenH.
Check this:Lars Vogel on n Eclipse Jobs and Background Processing[^]That describes it pretty well.
9 Apr 2012 by LucianoGonzalez97
I've searched on the internet for it but none of the articles I read explanated my question.I'm new to C# and VB.NET and I want to make a program to create new tasks on PocketOutlook (Windows mobile) setting Subject, date of conclusion and notes. Simply that.I just know that I need to...
26 Apr 2012 by andrew_dk
I've developed a COM+ server component (dll) that uses the ITaskScheduler and ITask interfaces to create and edit tasks for a specific .exe also created by the company I work for. The component is called from a classic ASP page (VBScript) and is part of an office package we are developing. The...
10 May 2012 by jsdhgkjdsahklg
Listen up.You can make a for loop or foreach loop that loops in the current processes, and then check the handle of each process and compare it with your application's.What you will face as a problem is that you can't kill all the processes, because some of them are you graphics card's and...
12 May 2012 by charles henington
Why not just delete all your system files will save you time in messing up the system.....just a thought.
15 May 2012 by visaokoten
Dear everyone,Anybody help about creat a task manager looklike task manager on windowBy VisualBaicThanks
14 Jun 2012 by Henning Dieterichs
Hello!Curr...
1 Jul 2012 by Henning Dieterichs
I've asked the question here[^] and get the solution: Now,...
27 Aug 2012 by kranthi1988
Hi all,Im working in SQL server 2000.Im trying to export the table data into excel file(file.xls defined destination data pump task).At the first time of execution file.xls creating successfully.And im trying to execute the package in next minit, it is showing error like 'file'...
10 Oct 2012 by Blake Miller
Do you impersonate the user prior to the COM calls?COM call could be executing in different thread, for which your impersonation is not set.
10 Oct 2012 by chaau
Make sure your IUsr_... user has SeImpersonatePrivilege privilege. The easiest way to check and/or set it is via secpol.msc. Go to User Rights Assignments->Impersonate a client after authentication and add the IUsr_... user there
12 Nov 2012 by Frazer Mann
Im trying to process data from my sql server in a chronological manner. The data is too large to fit into memory all at once so i have written a SProc which uses paging and returns X number of records.To speed up the processing, i create a collection of X number of tasks and assign them...
18 Nov 2012 by Member 9574034
According to code segment, is it thread safe? if not what should I do?Second, Is there any relation between number of cores of CPU and number of tasks?var t = new Task[2]{ Task.Factory.StartNew(()=> { foreach (var item in firstsortedlist) { ...
12 Dec 2012 by IviKAZAZI
Hello all,I have a console application which i run as a task,and i need to pass a parameter to it.Is there any workaround to do this from the task scheduler?Thanks in advance!
24 Dec 2012 by Oleksandr Kulchytskyi
Hi guys.I come here with one question related to Dispose method in Task class.How mandatory this method is ? And do i need to invoke it every time when i finished to work with task instance.I have investigated Dispose method with help of Reflector, and i found that internally when we...
24 Dec 2012 by OriginalGriff
It depends.Which may not be much help, but...You should call Dispose on any object which explicitly implements it, because the idea is that the object contains or uses resources which are in scarce supply, or which use a lot of "space" - be that memory or something else. If Dispose isn't...
18 Mar 2013 by Member 8288668
Hi everyone,I’m trying to build the “Applications” section of Task Manger using GetProcesses and then MainWindowTitle to filter GUI Applications. This worked well for me to begin with but I’ve now noticed that using “MainWindowTitle” does not always work because if an application has been...
18 Mar 2013 by Sergey Alexandrovich Kryukov
This is not true, it is not related to activation of a window. The problem appears when the application is not yet ready to expose the window handle; it's apparent than in early phases of application runtime a window handle is not even created; and, in more rare cases, some applications may...
27 Mar 2013 by Monica Agrawal
Hi I have a program that schedules task. While this runs fine on Windows7 machine, it throws an error on XP.Here is the code:using System;using System.Collections.Generic;using System.Linq;using System.Text;using TaskScheduler;namespace MyTaskScheduler{ class...
27 Mar 2013 by Dave Kreskowiak
There are two versions of the Task Scheduler API. Your TaskScheduler class is apparently using version 2.0, which doesn't exist on XP, only on Vista and above.
15 Apr 2013 by ANDiyo
Hello there,at the moment I am creating an application for desktopcomputers in offices. A user shall be abled to create tasks with the application on a specific server. But no user should have adminrights on the server. So I will create a adminuser on the server which I want to run the...
15 Apr 2013 by Marco Bertschi
Hi there,Not sure about it, but you might try this link for further information:http://superuser.com/questions/145575/automatically-run-an-application-as-another-user[^]
15 Apr 2013 by Maciej Los
If you want to run task with admini privileges, see these:http://stackoverflow.com/questions/2021831/admin-rights-for-a-single-method[^]http://stackoverflow.com/questions/4106628/start-process-with-administrator-right-in-c-sharp[^]Process p = new...
3 Jun 2013 by Dineshkumar Mohan
I want to do data validations like remove Dollar symbol, remove alpha numeric valuesin the columns. But data should not be moved to any other tables. Data sould be validated in the same table I.e., validations has to be done after loading the data to table.Any suggestion on how to do this?
4 Jun 2013 by E.F. Nijboer
Create a Data FLow Task, create a data source task and transfer it to an (In Memory) Recordset Destination. You can work on it from there and on success transfer it back.Good luck!
22 Jun 2013 by Rinion
I am trying to figure out the best approach in C# to allow a website that I have created to start up various programs on the server remotely, but not at the same time. I figured through .NET I could create a program that could react to various button clicks on the website, then populate a list...
25 Sep 2013 by azinyama
Good day all!!! I have a form where I'm entering the connection details to connect to an MSSql database. This is what I have done...private void sbTest_Click(object sender, EventArgs e) { if (!dxvpConnectionWizard.Validate()) return; ...
25 Sep 2013 by member 8888995
Hi Azinyama, You can use System.Data.SqlClient.SqlException class to catch exception from Database. Visit this link http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlexception.aspx[^]--Thanks
20 Dec 2013 by Yvan Rodrigues
The UI has a "loading" spinner. During the data loading below, the UI is responsive. During the LINQ, it freezes. The computer has 8 cores. public async static Task Load() { if (_loader == null) { _loader = Task.Run(() => ...
20 Dec 2013 by bowlturner
if you have visual studio 2012 or greater (.Net Framework 4.5 I think) you can use the Async keywords http://msdn.microsoft.com/en-us/library/hh156513.aspx[^]if not your mostly likely solution will be to put the linq on it's own thread.
12 Jan 2014 by thatraja
Member 10517109 wrote:Sorry, I did this quickly and thought it was only a forum for ToDoList by AbstractSpoon. I'm not writing code, this is just a usage question.Always post your question at bottom of that articleToDoList 6.8.5 Feature Release - An effective and flexible way to keep on top...
26 Feb 2014 by CHill60
Will these get you started?C# NotificationCenter[^]Notification Client and Server Written in C#[^]andhttp://stackoverflow.com/questions/2267916/notification-model-pattern[^]Not sure about this one but you never know until you try...
20 Mar 2014 by Kinna-10626331
Hi, I'm a beginner in automation tasks. I don't have experience on it.I have 2 scripts in C# (and one in CLI of CollabNetTeamForge,but for now we can forget about this last one).These scripts generate two XML docs which are connected and synchronized in a SharePoint Portal.I tested...
19 Mar 2014 by Yandy Zaldivar
Hi, I am going to give you two solution and you choose one or another depending in your needs. I didn't use your code demo as a guide but the text of your question.- Choose the ThreadApproach if you want to have explicit control over the thread that will run your task including the processor...
19 Mar 2014 by Hassue Rana
Simply create windows service and use timer in itit will run on ur cloud or server and at your specified interval your c# code will be run on cloud or server.I did this for one of my project a few years ago because asp.net or web services cant do this..
20 Mar 2014 by Kinna-10626331
If I have 2 C# pieces of code (VS Projects) witch return two XML docs . I want to program an automatic task what execute this 2 C# codes hourly and store the XMLs in order to keep updating the data . Is it possible to do this in a Unix server ? with CRON? Is it better with a Windows server?...
21 Mar 2014 by Member 10052408
I tried both methods , threadapproach and taskapproach, but i couldnt get two or more tasks start to run simultaneously because when i check cpu utilization, i see that only one of the specific processors is working with 100%, but what i want is two or more specific processors should work with...
25 Mar 2014 by Yandy Zaldivar
Hi, the problem in your design is that you are using a Processor level Affinity Mask. If you set if to 2, then all your threads will run on processor 2 and if you set it to 3, then all your threads will run on processor 3.If you want that thread 1 run on processor 2 and thread 2 run on...
30 Apr 2014 by 123456789igor
Hello, i try to write a simple asynchronous client/server apps. I know how do it using callback, but i want to invistigate how write client+server using await/async and c# 5.0. Please, help me. It should be simple. Only connect and transfer some bytes.I know that this can be done using...
1 May 2014 by 123456789igor
now server can send to client array of byte. But client recieved only 1 iteration. How i can do, that if client connected then it always recieve information from server?Server:public ServerSocket(IPAddress ipAddress, int port) { _server = new...
7 May 2014 by Piyush Jain618
This is the visual basic Script to import multiple excel files with different sheet names into single SQL table. Here is the Steps to be followed:-Step 1:- Create a multiple excel sheets with different name and different sheet name.NOTE:- All Excel files and sheets have same...
13 May 2014 by OriginalGriff
OK:public List List { get; set; }Other than that, it's a bad idea to expose a collection directly, and it could use either code in the class constructor to create an empty list by default, or a backing field rather than using an automatic property. I'd also make the setter...
10 Jun 2014 by Member 10877014
Hi,We got application which assigned the outlook tasks to person using database data. We want to update taskitem if date in database changes. As taskitem is assigned it gives error "You do not own this task. Your changes may be overwritten by owner of task."We want to update assigned...
2 Jul 2014 by mathiazhagan01
I have 2 AsyncTask, one was nested inside other in the loop, I want to invisible the progress bar and also do other functions after both AsyncTask is finished. I don't know how to do that? Please help me.public class GalleryFragment extends Fragment { ProgressBar...
2 Jul 2014 by Peter Leow
You have been posting 6 different homework in the last couple of minutes. You have seriously got the wrong idea. This is a quick answers forum that helps fellow programmer to learn to solve specific coding issue. We do not do your homework. We are not helping you if we do. The purpose of...
7 Jul 2014 by fabio_antonio
Hello everybody, I am trying to make a simple container for a group of processes using the Linux's kernel feature: CGroups. I managed to create a group and properly set the memory.limit_in_bytes and memory.memsw.limit_in_bytes parameters to a given limit.My dummy program just allocates memory...
12 Jul 2014 by Maciej Los
Have a look here: Update Outlook taskitem Programatically[^]
21 Jul 2014 by Mohammed Abdul Mateen
Hi,We're creating a WPF app in which we execute python scripts from different Test Stations and show the output in its corresponding output panel, To run the scripts in parallel we are using Task but when we run the scripts in parallel from the stations, We are getting the output of other...
21 Jul 2014 by Nagy Vilmos
There is a lot missing from your code, but I will hazard a guess that you need to check the socket you send the reply out to. I am guessing that whatever socket you read the inbound message from, the reply is always sent to the first one created.As each connection is made, hold the socket...
31 Jul 2014 by Mehdi Gholam
Threads are resource expensive so assigning one to each customer is not scalable but having a pool of threads (usually much lower than the number of customers) and assigning work to those threads is per request is.Tasks are lighter weight processing units which work on threads in the...
7 Aug 2014 by Yannick Brodard
So I have this command :public DelegateCommand GenerateReportForAllClientsCommand { get; set; }public bool CanExecuteGenerateReportForAllClients(){ return true;}public async void GenerateReportForAllClientsExecute(){ if (ClientList.Count