Thread C# with Example



Thread C# with Example

See below for a simple example of how to use a Thread to do some time intensive stuff in a background process. 
public async void ProcessDataAsync() 
{ 
// Start the time intensive method 
Thread t = new Thread(TimeintensiveMethod); 
//  Control  returns  here  before  TimeintensiveMethod  returns 
Console.WriteLine("You can read this while TimeintensiveMethod is still running."); 
} 
private void TimeintensiveMethod() 
{ 
Console.WriteLine("Start TimeintensiveMethod."); 
//  Do  some  time  intensive  calculations... 
using (StreamReader reader = new StreamReader(@"PATH_TO_SOME_FILE")) 
{ 
string v = reader.ReadToEnd(); 
for (int i = 0; i < 10000; i++) 
v.GetHashCode(); 
} 
Console.WriteLine("End TimeintensiveMethod."); 
} 
As you can see we can not return a value from our TimeIntensiveMethod because Thread expects a void Method as 
its parameter. 
To get a return value from a Thread use either an event or the following: 
int ret; 
Thread t= new Thread(() => 
{ 
Console.WriteLine("Start TimeintensiveMethod."); 
//  Do  some  time  intensive  calculations... 
using (StreamReader reader = new StreamReader(file)) 
{ 
string s = reader.ReadToEnd(); 
for (int i = 0; i < 10000; i++) 
s.GetHashCode(); 
} 
Console.WriteLine("End TimeintensiveMethod."); 
// return something to demonstrate the coolness of await-async 
ret = new Random().Next(100); 
}); 
t.Start(); 
t.Join(1000); 
Console.Writeline("Count: " + ret); 
 

In C#, a method declared async won't block within a synchronous process, in case of you're using I/O based 
operations (e.g. web access, working with files, ...). The result of such async marked methods may be awaited via 
the use of the awaitkeyword. 

0 Comment's

Comment Form

Submit Comment