Delay a block of code [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
In my WebApi project I have an endpoint that should delay a small block of code.
Let's make an example:
I need to implement a mechanism that permit the client to book for a resource. The booking time should only have a duration of 120 seconds and then expire.
In terms of code I have something like this:
//booking
foreach (var item in list) {
item.Status = ItemStatus.Booked;
}
await _context.SaveChangesAsync();
//Setup a delayed "thread" which removes the booking
Task.Delay( TimeSpan.FromMinutes( 2 ) )
.ContinueWith( x => {
//loop on the list and set the status to "ReadyForSale"
//if this is still in the Booking
} );
return;
I would like to understand if a solution like this satisfy my requirement. The current thread should not be blocked from the delayed task and I need to find a way to pass the list of items to the delayed task.

I think there is a risk that the task will never run. What if the sever crashes or IIS decides it needs to recycle the pool.
There is the risk that the state would never be restored.
I would probably set a bokedAt DateTime field in the database and then check if that time compared to now is more than two minutes to determine if the item is booked or not. Perhaps even a computed column that checks this and returns the state.

Related

Easy and correct way to loop accounts [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 2 years ago.
Improve this question
I am creating a bot for a website where the system logs in with several accounts and does a certain action the problem is when it is time to repeat the process example I have 10 accounts and I would like all accounts to do the same process as the first, the accounts are browned in a txt file. What is the correct way to do this?
Sometimes the function runs ahead of time, I'm new to C # I'm studying
My code looping :/
Task.Delay(2000).ContinueWith(t => setMail());
Task.Delay(3500).ContinueWith(t => nextButton());
Task.Delay(5000).ContinueWith(t => setPass());
Task.Delay(6500).ContinueWith(t => logionButton());
Task.Delay(7500).ContinueWith(t => SucessLogin());
You are creating 5 independent tasks which will all run together, rather than one after the other. Instead, just collapse them to one async/await function:
async Task TestStuff(Account account)
{
await Task.Delay(2000);
setMail();
await Task.Delay(3500);
nextButton();
await Task.Delay(5000);
setPass();
await Task.Delay(6500)
logionButton();
await Task.Delay(7500);
SucessLogin();
}
You mentioned that you've got accounts stored in a file. In this example you'll need to create an Account class and populate it with the information you get from the file. For example:
List<Account> accounts = LoadAccounts("some-file.txt")
foreach(var account in accounts)
{
await TestStuff(account);
}

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.

function repetition every 15 minutes c# [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 6 years ago.
Improve this question
I'm doing some masks for SAP B1 using c#.
I'd need to know how to create a function that, automatically (for examples every 15 minutes), take some data and put its on a database.
The function is already done but how can I create the automatic execution in background?
Best regards and thanks in advance for the reply,
Lorenzo
Timer is what you need:
var timer = new System.Threading.Timer(
e => Method(),
null,
TimeSpan.Zero,
TimeSpan.FromMinutes(15));
This will call Method() every 15 minutes.
Timer info : https://msdn.microsoft.com/en-us/library/system.threading.timer.aspx
You could use Timer like #AmbroishPathak suggested. Also, as mentioned in the comments, you can use the Windows Task Scheduler to run your script or executable. The advantage of this is that the process won't be running in the background while it's not doing work.
You can see the details of how to schedule a task here.
The following answer describes this as well: windows scheduler to run a task every x-minutes?
To summarize the accepted answer there, you create the task to run once a day. After that, you can double-click on the task to bring up its Properties window and go to the "Triggers" tab. Under "Advanced Settings" you should be able to set it to run every x number of minutes.

C# Task Factory [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 7 years ago.
Improve this question
Hi I have code like below in a for loop. It is in a for loop because the number of times it needs to be run can vary dependent on how many items the user has added.
var taskList = new List<Task<IEnumerable<MyObject>>>();
for (int i = 0; i < numOfBatches; i++)
{
var task = Task.Factory.StartNew(() => MyMethod(variableA, variableB));
taskList.Add(task);
}
//Wait for all the tasks to complete
Task.WaitAll(taskList.Cast<Task>().ToArray());
return taskList.SelectMany(x => x.Result);
Is there a better way I can run these tasks in Parallel? I was thinking about a parallel for each loop but because the number of iterations of the loops isn't fixed I don't think I can use a parallel for each
There isn't necessarily a problem with the code. However if I have 10,000 items inputted it takes about 18 minutes and I was thinking if I could run the Tasks in parallel it may return faster. If 10,000 items are inputted the number of batches will be 10,000/25 = 400
The actuall code in MyMethod calls a 3rd party external service to return data based on data entered by user
Processing a list in parallel is about the easiest of parallel algorithms there is:
ParallelEnumerable.Range(0, numOfBatches)
.Select(_ => MyMethod(variableA, variableB))
.ToList();
It is a code smell to create unbounded numbers of tasks because this can lead to resource exhaustion and the code is clumsy.

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