In my recent project we had a requirement to run the multiple threads background without disturbing the front end user C#. We can implement this in number of ways in C#, for example we can start multiple threads by using System.Threading namespace. In this example we will discuss how to run multiple threads without front user knowledge by using Task.Factory.StartNew in C#.
Open Microsoft Visual Studio 2015 => Create New Console Application and name it as CSharpTaskStartNew.
Here we will create some text files and will write content to each file independently. That means our program in a way that it creates the files and write the content to the files in separate process as shown below.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace CSharpTaskStartNew
{
class Program
{
static void Main(string[] args)
{
List<Task> TaskList = new List<Task>();
for (int i = 0; i <= 10000; i++)
{
string sFilePath = @"E:\Data\File_" + i.ToString() + ".txt";
File.Create(sFilePath).Dispose();
TaskList.Add(Task.Factory.StartNew(() => WriteToFile(sFilePath)));
}
Task.WaitAll(TaskList.ToArray());
}
private static void WriteToFile(string sFilePath)
{
for (Int64 i = 0; i <= 10000; i++)
{
StreamWriter fileStream = new StreamWriter(sFilePath, true);
fileStream.WriteLine("Line - " + i.ToString() + Environment.NewLine);
fileStream.Close();
}
}
}
}
As shown above we created the separate process for each file to write the content on it. Because of this content will get loaded into files simultaneously as shown below.
We can use Task.Factory.StartNew() to send the emails to users and we can run on multiple tasks where one task does not depends on other.