Asyn and Await to write to a File .
Using Async and Await (Asynchronous programming to ) write to files in a synchronous manner one .by creating 4 child threads (Task) existing from the threadpool.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
namespace CLRprof
{
class asyncawait
{
public Task Longrunningprocess(string filename,string text)
{
return Task.Run(() =>
{
Monitor.Enter(this);
using (StreamWriter writer = new StreamWriter(filename, true))
{
writer.Write(text);
writer.Close();
Monitor.Exit(this);
Thread.Sleep(1000);
Console.WriteLine("Finished the Longrunning process");
}
});
}
public async void CallProcess()
{
await Longrunningprocess("shared.txt", "Write for me first1");
await Longrunningprocess("shared.txt", "Write for me first2");
await Longrunningprocess("shared.txt", "Write for me first3");
await Longrunningprocess("shared.txt", "Write for me first4");
Console.WriteLine("Finished");
}
}
class program
{
public static void Main()
{
asyncawait a = new asyncawait();
a.CallProcess();
Console.WriteLine("Main thread Finished");
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
namespace CLRprof
{
class asyncawait
{
public Task Longrunningprocess(string filename,string text)
{
return Task.Run(() =>
{
Monitor.Enter(this);
using (StreamWriter writer = new StreamWriter(filename, true))
{
writer.Write(text);
writer.Close();
Monitor.Exit(this);
Thread.Sleep(1000);
Console.WriteLine("Finished the Longrunning process");
}
});
}
public async void CallProcess()
{
await Longrunningprocess("shared.txt", "Write for me first1");
await Longrunningprocess("shared.txt", "Write for me first2");
await Longrunningprocess("shared.txt", "Write for me first3");
await Longrunningprocess("shared.txt", "Write for me first4");
Console.WriteLine("Finished");
}
}
class program
{
public static void Main()
{
asyncawait a = new asyncawait();
a.CallProcess();
Console.WriteLine("Main thread Finished");
Console.ReadLine();
}
}
}
Comments
Post a Comment