patterncsharpMinor
“Proper” Asynchronous implementation
Viewed 0 times
properimplementationasynchronous
Problem
I need some opinion if my code below is proper for an async process. This code only reformats text. Please let me know if this implementation is not proper or needs some improvement.
static void Main(string[] args)
{
Task.Factory.StartNew(() => ReadCharacter("File 1.txt"));
Task.Factory.StartNew(() => ReadCharacter("File 2.txt"));
Console.WriteLine("Main Task");
Console.ReadLine();
}
static void ReadCharacter(string inputFile)
{
string result;
using (StreamReader sr = new StreamReader(inputFile))
using (StreamWriter sw = new StreamWriter(string.Format("C:\\Out--{0}",inputFile)))
{
Console.WriteLine("Opening file : {0}", inputFile.ToString());
while (!sr.EndOfStream)
{
result = sr.ReadLine();
sw.WriteLine(string.Format("{0} --> {1}",result,Task.CurrentId.ToString()));
}
Console.WriteLine("Finish {0}", inputFile);
sr.Close(); sw.Close();
}
}Solution
Well, you start two
-
-
Your worker method
-
You hard-code your output directory to
Tasks each reading and writing a file but not the same. So basically it should be ok. Some remarks:-
Task.Factory.StartNew returns a Task. You probably want to wait until the tasks you have started are finished before you quit from main which you can do with Task.WaitAll. Something along these lines:var task1 = Task.Factory.StartNew(() => ReadCharacter("File 1.txt"));
var task2 = Task.Factory.StartNew(() => ReadCharacter("File 2.txt"));
Console.WriteLine("Main - waiting for tasks to finish");
Task.WaitAll(task1, task2);
Console.WriteLine("Finished");-
Your worker method
ReadCharacter writes directly to the console. What happens if you want to run this code in a windows service process where this should be logged instead? So you should pass some kind of ILogger to the method and use that to output the status/log messages.-
You hard-code your output directory to
C:\. This should really be passed in as destination folder.Code Snippets
var task1 = Task.Factory.StartNew(() => ReadCharacter("File 1.txt"));
var task2 = Task.Factory.StartNew(() => ReadCharacter("File 2.txt"));
Console.WriteLine("Main - waiting for tasks to finish");
Task.WaitAll(task1, task2);
Console.WriteLine("Finished");Context
StackExchange Code Review Q#36487, answer score: 6
Revisions (0)
No revisions yet.