Best way to do a multithread foreach loop [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 9 years ago.
Improve this question
I have a send email method with a foreach, like this:
static void Main(string[] args)
{
foreach(var user in GetAllUsers())
{
SendMail(user.Email);
}
}
I need to improve that method. Using a multithread, because i dont want to wait the SendMail method executes each time for each user.
Any sugestions to do that?
Thanks

Try using a parallel foreach. I.e.
Parallel.ForEach(GetAllUsers(), user=>
{
SendMail(user.Email);
});

You can try something like this
private void Send()
{
Parallel.Foreach(GetAllUsers(), user =>
{
SendMail(user.Email);
});
}

I think the easiest way to do this would be thread pooling. .Net makes this pretty easy and you can read more about it here.

Related

new with delegates and lambda expressions [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 6 years ago.
Improve this question
Basically I want to create a method that can return a string message regarding on what currently happening inside a method
example:
public MainMethod()
{
//Execute One
//Execute Two
//Execute Three
}
upon using it I'm thinking of like this
something = delegate (string message) {console.writeline("{0}",message)};
the output would be
Execute One
Execute Two
Execute Three
Is this possible using delegate or lambda? if yes can I ask for an example on how I should correctly implement this? if no please help me with alternative.
Thanks
Use Func and Action. They make interacting with delegates much easier. Funcs have return values, Actions do not:
public MainMethod()
{
Action<string> writerAction = (message) => Console.WriteLine(message);
writerAction("Execute One");
writerAction("Execute Two");
writerAction("Execute Three");
}

C# How to pause program [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 8 years ago.
Improve this question
I have simple question. How do I pause program? I want to change pictures very slowly.
My code:
private void button2_Click(object sender, EventArgs e){
Image picture1 = Program.Properties.Resources.picture1;
Image picture2 = Program.Properties.Resources.picture2;
Button1.Image = picture1
//Here I want pause
Button1.Image = picture2
}
If you want procedural code (like in your example), without timers and without locking the UI:
await Task.Delay(1000)
You can use Threads or Timers.
http://msdn.microsoft.com/en-us/library/swx5easy.aspx
http://programmingbaba.com/how-to-stop-system-threading-timer-in-c-do-net/
Or you can use Sleep method to puase your program.
http://www.dotnetperls.com/sleep

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.

Create Random User algorithm in c# [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 8 years ago.
Improve this question
i want to create users based on the number of photos in a folder.
for example:
user.1 random(4)[photos1-4]
dosomething(user.1)
user.2 random(6)[photos5-10]
dosomething(user.2)
user.3 random(3)[photos11-13]
dosomething(user.3)
user.last [photos.leftover]
dosomething(user.last)
ideas on how to do this?
The best way to do this is load your list of work, randomize the list, then put the list in to a queue of some form to be pulled out by the end workers.
private BlockingCollection<string> GetWorkSoruce()
{
List<string> sourceList = GetListOfFiles(); //How you get your list is up to you.
Shuffle(sourceList); //see http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp
//Create a thread safe queue that many consumers can pull from.
var collection = BlockingCollection<string>(new ConcurrentQueue<string>(sourceList));
collection.CompleteAdding();
return collection;
}
Now each of your workers (Users) can pull out of the queue and be given work to do. Because the queue is a ConcurrentQueue you can have many workers from many threads all working at the same time.
private void WorkerDoWork(BlockingCollection<string> workSource, int itemsToTake)
{
foreach(var imagePath in workSource.GetConsumingEnumerable().Take(itemsToTake))
{
ProcessImage(imagePath);
}
}

Parallel processing [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 9 years ago.
Improve this question
I have a list of sites for which log files are generated. These logs have to be robocopied, unzipped, parsed and analysed with ruby code by running respective processes.
Can anybody suggest the best way to run these processes in parallel for all the site's logs?
Considering your data model like this:
class Website
{
public List<WebSiteLog> Logs;
}
A possible parallel solution using TPL (Task Parallel Library) is something like this:
// var sites = your sites list
var processTask = Task.Foreach(sites, site =>
{
Task.Factory.StartNew(theSite=>
{
theSite.UnzipLogs()
}.ContinueWith(unzipTask=>{
{
theSite.ParseLogs();
}.ContinueWith(parseTask=>{
{
theSite.AnalyzeLogs();
}
});
Task.WaitAll(processTask);
This is a very initial solution. Lots of exception management, partitioning and even more paralellizing on UnzipLogs, ParseLogs, AnalyzeLogs are applicable.

Categories