Run a piece of code while the main program is running [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I was making a game on C# just for practice and learning (first program in C#) and I wondered if it was possible for C# to let me, while my program (the game) is running to simultaneously run another piece of code that would be the background music (just some Console.Beep() basic stuff).
In short, my question is if it would be possible for both the code for the background music and the one for the game to be in the same program, and if not, if there is an easy way to make it in just one console.

There are many options for threading. One of the most simpler are just using Task()
// Here I store the token for future use
processMe = new MyBackgroundProcess(ERPManager.CancellationTS.Token);
var aTask = new Task(() =>
{ // Everything here runs on another thread
processMe.Run();
}, ERPManager.CancellationTS.Token);
In this case, the "Run" method will run on a separte thread.
The "Token" is for cancelling the task. "processMe" stores the reference and asks "I am cancelled?"
For example, let's say Run() is like
public void Run()
{
while (! token.IsCancellationRequested)
{
PlayMusicSlice();
}
}
So you check if it's cancelled. When you finish, you just do a
ERPManager.CancellationTS.Cancel()
On your main thread.
You can play with things like
List<Task> tasks = new List<Task> ();
tasks.Add(new Task(() => Process1.Run(), aCancellationToken));
tasks.Add(new Task(() => Process2.Run(), aCancellationToken));
tasks.Add(new Task(() => Process3.Run(), aCancellationToken));
And then do
Task.WaitAll(tasks.ToArray());
Or
Task.WaitAny(tasks.ToArray());
And then query the status
if (tasks[0].IsCompleted()) { ... }
if (tasks[0].IsFaulted()) { ... }
You will face a lot of issues like concurrency and problems accessing UI elements, but this is a good start :)

Related

C# Thread.Run inside For loop what is the behavior [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I making an Experiment, I have a loop of 100000 increments and inside it there is a thread that does a specific task(write a log to DB), my question is when I run it its finish in one second maybe and it start to insert them lately, then how the OS handles them and it will process them all or will skip from them?
I try awaited method with them its good. but I want to know what will happen if this code was on a server and received 100000 requests.
The Code:
for (int i = 0; i < 100000; i++)
{
Task.Run(() => log.WriteToLog(i + "", new Models.CustomerModel.CustomerModel()));
}
I am not looking for alternative ways, I need to know the behaviour and how this code handles in OS (if there is a queue, some of them will run, etc..)
PS: I know its not a good approach
1 second is a bit quick. I suspect you are not logging 100000 entries properly and entries are being lost.
Assuming that code was the only code inside say a console app's main(), then because you don't await any of the tasks, it is entirely possible your process is exiting before the logging is complete.
Change:
Task.Run(() => log.WriteToLog(i + "",
new Models.CustomerModel.CustomerModel()));
...to:
await Task.Run(() => log.WriteToLog(i + "",
new Models.CustomerModel.CustomerModel()));
Also, as ckuri mentions in the comments, spawning a great deal of tasks in a tight loop probably isn't a good idea. Consider batching the logging or using IOCP.

Pull and Push Data in .Net, in parallel [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So far I have only written single core programs. Now I want to improve my performance and trying to find out, how to pull and push data parallelized. But I even don't know whether I have the right idea about MultiThreading.
Actually it is a pretty simple case. I pull data from an external interface, rework them so that they are in the right order and push them into an OpenGL Pipeline in order to draw them.
I use a WPF-application as GUI and render my data with SharpGL(OpenGL wrapped). the program runs on a dual-core processor.
Here is a sketch of my vision.
So my idea is to use a bufferArray. Now the clue: How could I write and read in the same array from different thrads?
I was recommended to inform about OpenMP. But as it turned out it is not a good idea for .Net and C#.
Thus could you recommend some fitting papers? Maybe an explanation how to use Task Parallel Library (TPL) for this case.
The correct description for this is the producer consumer pattern. In .Net you can do this using TPL Dataflow
Another implementation can be build using a BlockingCollection. A basic version:
BlockingCollection<int> bc = new BlockingCollection<int>();
async Task Main()
{
// Fire up two readers
Task.Run(() => ReadCollection1());
Task.Run(() => ReadCollection2());
// Add items to process.
bc.Add(5);
bc.Add(6);
bc.Add(7);
bc.Add(8);
bc.Add(9);
bc.CompleteAdding(); // Signal we are finished adding items (on close of application for example)
}
void ReadCollection1()
{
foreach (var item in bc.GetConsumingEnumerable())
{
$"1 processed {item}".Dump();
}
}
void ReadCollection2()
{
foreach (var item in bc.GetConsumingEnumerable())
{
$"2 processed {item}".Dump();
}
}

C# Prevent async task from being run again before finishing [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I cant seem to find the information that im looking for in the documentation and could use a second pair of eyes. I would like to do this without testing; only a visual examination and theory discussion.
My draft attempt sets a bool which will only allow an async method to be run if the returned task sets its value to Task.IsCompleted. My question is, will this code do what I assume it will and if not, what is an alternative that will perform only a single call at a time? (assuming the infinite loop and async task remain unchanged)
You may fairly assume that RunAsync() is an asynchronous method, denoted by the async keyword, containing an awaitable task which returns a Task instance.
bool asyncOutputCallAllowed = true;
while (true)
{
if (asyncOutputCallAllowed)
{
asyncOutputCallAllowed = false;
asyncOutputCallAllowed = RunAsync().IsCompleted;
}
}
I am guessing that you are trying to do the following: make an async call, keep looping and doing other stuff while also waiting for async-task to finish, and then start a new async task when the previous one finishes. If so, then you probably want something along the following lines:
Task activeOperation = null;
while (true)
{
if (activeOperation == null)
{
// No async operation in progress. Start a new one.
activeOperation = RunAsync();
}
else if (activeOperation.IsCompleted)
{
// Do something with the result.
// Clear active operation so that we get a new one
// in the next iteration.
activeOperation = null;
}
// Do some other stuff
}
Depending on your exact algorithm, you might want to start the new task in the same iteration in which the previous one finishes. That is just a small tweak of the above.
If you are not doing anything else in the loop except wait for the async-task, then you can get rid of the loop entirely and use a continuation instead (see ContinueWith).

In an ASP.NET app execute methods on multiple threads [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have an ASP.NET app, where a single request invokes 6 very slow methods. The methods are not async and I don't have the time to rewrite and test them. How can I run those 6 methods on 6 threads and then agregate the results? I'm on .NET 4.5.
You can simply use Task.Run to create a task that runs each of the methods in another thread, and then wait for them all to finish so that you can use the results.
var tasks = new Task<YourResultType>[]
{
Task.Run(() => Method1()),
Task.Run(() => Method2()),
Task.Run(() => Method3()),
Task.Run(() => Method4()),
Task.Run(() => Method5()),
Task.Run(() => Method6()),
};
var results = Task.WhenAll(tasks).Result;
If the methods don't all have results of the same type, allowing you to put all of the tasks into an array, then you'll need to have separate local variables for each task and use Result on each one after starting them all.

Async await foreach issue [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
private async void btnLoadFile_Click(object sender, EventArgs e)
{
if(AccountsFile.ShowDialog()==DialogResult.OK)
{
Accounts = File.ReadAllLines(AccountsFile.FileName);
foreach(string str in Accounts)
{
await LoadAccount(str);
}
}
}
I've ran into a problem, I know how Asynchronous programming works it will wait for the task to be complete but LoadAccount() will never complete because it calls a function with a never ending while loop so it will not reach the next string in Accounts.
I don't know where to start with this problem. Any solutions?
Instead of waiting for each account successively, you could wait for them collectively. This way, even if one of your accounts enters an infinite loop, the others could still proceed to load.
Accounts = File.ReadAllLines(AccountsFile.FileName);
Task completionTask = Task.WhenAll(Accounts.Select(LoadAccount));
You would typically want to store completionTask in a class variable. Subsequently, when you break out of the indefinite while loop within your LoadAccount calls (for example, by signalling cancellation via a polled CancellationToken), you can use this completionTask to wait for all your tasks to complete.

Categories