Call method inside multiple tasks C# - c#

I am having a problem calling a method in a list of Tasks. I have a method that creates N number of tasks. In each task I perform some operations that in the end results an fetching data via HttpWebRequest and writing that data into a file. I use lock objects to lock the access to shared resources like variables. Everything performs great except the call for a method that creates a executes an HttpWebRequest (method GetData). Whenever I don't lock that call for the method (GetData) it seems that some data/files are skipped. For example:
With the lock object I get file 1,2,3 and 4
Without the lock object I get file 2,4 and 3
Here's the code for the method that creates the tasks
private object lockObjectWebRequest= new object();
private object lockObjectTransactions = new object();
public List<Task> ExtractLoanTransactionsData(string URLReceived, string Headers, string Body)
{
List<Task> Tasks = new List<Task>();
try
{
int Limit = 0;
int OffsetItemsTotal = 0;
int NumberOftasks = 4;
// Create the task to run in parallel
for (int i = 0; i <= NumberOftasks; i++)
{
int OffsetCalculated = 0;
if (i > 0)
{
OffsetCalculated = Limit * i;
}
Tasks.Add(Task.Factory.StartNew(() =>
{
string URL = URLReceived+ "&offset=" + OffsetCalculated .ToString() + "&limit=" + Limit.ToString();
string Output = string.Empty;
lock (lockObjectWebRequest)
{
Output = GetData(URL, Headers,Body);
}
if (Output != "[]")
{
lock (lockObjectTransactions)
{
Identifier++;
Job.Identifier = Identifier;
// write to file
string json = JValue.Parse(Output).ToString(Formatting.Indented);
string FileName = OffSet.ToString() + Identifier;
string Path = #"C:\FileFolder\" + FileName + ".json";
File.WriteAllText(Path, json);
}
}
}));
}
}
catch (Exception ex)
{
Tasks = new List<Task>();
}
return Tasks;
}
Here's the code that performs the HttpWebRequest:
public string GetData(string URL, string Headers, string Body)
{
string Data = string.Empty;
Headers = Headers.Trim('{').Trim('}');
string[] HeadersSplit = Headers.Split(new char[] { ',', ':' });
HttpWebRequest WebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
WebRequest.Credentials = new NetworkCredential();
WebRequest.Method = "POST";
HttpWebResponse WebResponse;
// Set necessary Request Headers
for (int i = 0; i < HeadersSplit.Length; i = i + 2)
{
string HeaderPart1 = HeadersSplit[i].Replace("\"", "").Trim();
string HeaderPart2 = HeadersSplit[i + 1].Replace("\"", "").Trim();
if (HeaderPart1 == "Content-Type")
{
WebRequest.ContentType = HeaderPart2;
}
else if (HeaderPart1 == "Accept")
{
WebRequest.Accept = HeaderPart2;
}
else if (HeaderPart1 == "Authorization")
{
WebRequest.Headers["Authorization"] = HeaderPart2;
}
}
WebRequest.Headers.Add("cache-control", "no-cache");
// Add body to Request
using (var streamWriter = new StreamWriter(WebRequest.GetRequestStream()))
{
streamWriter.Write(Body);
streamWriter.Flush();
streamWriter.Close();
}
// Execute Request
WebResponse = (HttpWebResponse)WebRequest.GetResponse();
// Validate Response
if (WebResponse.StatusCode == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(WebResponse.GetResponseStream()))
{
Data = streamReader.ReadToEnd();
}
}
return Data;
}
What am I doing wrong here? The method doesn't have global data that is shared between tasks.

But you do have data that is shared between the tasks: the local varibleIdentifier and the method argument Job.
You are writing to a file using the Identifier in the file-name. If the lock is not in place, that piece of code will be running simultaniously.
The implications for Job can't be deduced from your question.
I think you can solve the identifier problem by doing this:
var identifier = Interlocked.Increment(ref Identifier);
Job.Identifier = identifier; // Use 'identifier', not 'Identifier'
// write to file
string json = ...;
string FileName = OffSet.ToString() + "_" +
"MAMBU_LT_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" +
identifier; // Use 'identifier', not 'Identifier'
...

Related

How to skip System.InvalidOperationException when application running on C#?

I have used thread , task function to remove UI block after method is executing. I used following code but it gave me System.InvalidOperationException. Here is code I tried:
private void FindVariation()
{
string[] idlist = richTextBox7.Text.Split('\n'); // < == System.InvalidOperationException
// foreach (string id in idlist)
for (int i = 0; i < Convert.ToInt32(idlist.Length); i++)
{
string url = "http://www.ebay.com/itm/" + idlist[i];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
// richTextBox2.Text += sr.ReadToEnd();
string a = sr.ReadToEnd();
sr.Close();
string source = null;
source = string.Join(Environment.NewLine,
a.Split(',', ']', '[')
.Where(m => m.Length == 12 && m.All(char.IsDigit)));
if (string.IsNullOrEmpty(source))
{
// MessageBox.Show("String is null");
}
else
{
richTextBox6.Text += idlist[i] + Environment.NewLine;
}
richTextBox1.Text = richTextBox7.Text;
}
}
Task fv = new Task(FindVariation);
fv.Start();
Could anybody show me what is the error?
Here's the kind of approach you need:
async Task Main()
{
string input = richTextBox7.Text;
string result = await Task.Run(() => FindVariation(input));
richTextBox1.Text = result;
}
private string FindVariation(string richTextBox7Text)
{
string[] idlist = richTextBox7Text.Split('\n');
//your code - but no access to any UI element.
return result;
}
The key thing is that inside the FindVariation you cannot access or update any UI element. Everything has to be passed in or passed out before UI is updated.

Connection reset issue in .net core api call (net::ERR_CONNECTION_RESET 200 (OK))

I have a .net core API service which is called from a angular client project.
When a user request a status of his payment, we will make call to this service api and this service will then call a payment gateway service to fetch the status of payment and the output result will return to the user.
When i try to integrate this i am facing this below error.
net::ERR_CONNECTION_RESET 200 (OK)
core.js:5967 ERROR Unknown Error
This above issue is not showing when i try to hit the service after putting one breakpoint. Its also returning the result.
This is how entire flow works
Client side call performs by user
this.dataservice.postFeed(method, JSON.stringify(this.initsearch)).subscribe(result => {
var response = result.body["data"];
console.log(response);
});
Server side code looks like
[HttpPost]
public async Task<IActionResult> Post([FromBody] ObjectModel searchValue)
{
ApiResponse<string> response = new ApiResponse<string>();
IBaseResult<string> result = await _adlerBo.GetPaymentStatus(searchValue);
response.Success = result.success;
response.Data = result.Data;
return Ok(response);
}
In BusinessObject.cs
public async Task<IBaseResult<string>> GetPaymentStatus(PaymentSearchModel requestModel){
string apiResponse = await PaymentStatusCheckUsingAPI(requestModel.orderid);
return apiResponse ;
}
private async Task<string> PaymentStatusCheckUsingAPI(string orderNumber)
{
string message = await PostPaymentRequestToGateway(statusApiUrl, authQueryUrlParam);
NameValueCollection param = await GetResponseMap(message);
string status = "";
string encResJson = "";
if (param != null && param.Count == 2)
{
for (int i = 0; i < param.Count; i++)
{
if ("status".Equals(param.Keys[i]))
{
status = param[i];
}
if ("enc_response".Equals(param.Keys[i]))
{
encResJson = param[i];
}
}
if (!"".Equals(status) && status.Equals("0"))
{
resJson = crypto.Decrypt(encResJson, workingKey);
}
else if (!"".Equals(status) && status.Equals("1"))
{
Console.WriteLine("failure response: " + encResJson);
}
}
return resJson;
}
private async Task<string> PostPaymentRequestToGateway(string queryUrl, string urlParam)
{
string message = "";
try
{
StreamWriter myWriter = null;// it will open a http connection with provided url
WebRequest objRequest = WebRequest.Create(queryUrl);//send data using objxmlhttp object
objRequest.Method = "POST";
//objRequest.ContentLength = TranRequest.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";//to set content type
myWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
myWriter.Write(urlParam);//send data
myWriter.Close();//closed the myWriter object
// Getting Response
System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();//receive the responce from objxmlhttp object
using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
{
message = await sr.ReadToEndAsync();
//Response.Write(message);
}
}
catch (Exception exception)
{
Console.Write("Exception occured while connection." + exception);
}
return message;
}
private async Task<NameValueCollection> GetResponseMap(string message)
{
//await Task.Delay(2000); I did this with no Luck
NameValueCollection Params = new NameValueCollection();
if (message != null || !"".Equals(message))
{
string[] segments = message.Split('&');
foreach (string seg in segments)
{
string[] parts = seg.Split('=');
if (parts.Length > 0)
{
string Key = parts[0].Trim();
string Value = parts[1].Trim();
Params.Add(Key, Value);
}
}
}
return await Task.FromResult(Params);
}
Any idea how to fix this? Why its working when i put breakpoint and not otherwise.
Am i doing correct asynchronous implimentsion in my api?

Handling Parallel POST to API

I have a API Post method that takes is a string which represents a Bae64 string of bytes from a word document that the API converts to PDF. My test client sends multiple documents, each on its own task, to the API to be converted. The problem is with concurrency and writing the files. I end up with a file in use since the calls are parallel. I have tried a lot of different way to block the conversion process until a document is converted but none of it has worked. Everything works fine if it's jsut a single file being converted but as soon as it's 2 or more, the problem happens. Can anyone guide me in the correct direction to solve this issue?
API:
[HttpPost]
public async Task<SimpleResponse> Post([FromBody]string request)
{
var response = new SimpleResponse();
Task t = Task.Factory.StartNew(async () =>
{
try
{
Converter convert = new Converter();
var result = await convert.CovertDocToPDF(request, WebConfigurationManager.AppSettings["tempDocPath"], WebConfigurationManager.AppSettings["tempPdfPath"]);
response.Result = result;
response.Success = true;
}
catch (Exception ex)
{
response.Exception = ex;
response.Success = false;
response.Errors = new List<string>();
response.Errors.Add(string.Format("{0}, {1}", ex.Message, ex.InnerException?.Message ?? ""));
}
});
t.Wait();
return response;
}
Conversion code
public Task<string> CovertDocToPDF(string blob, string tempDocPath, string tempPdfPath)
{
try
{
// Convert blob back to bytes
byte[] bte = Convert.FromBase64String(blob);
// Process and return blob
return Process(bte, tempDocPath, tempPdfPath);
}
catch (Exception Ex)
{
throw Ex;
}
}
private async Task<string> Process(byte[] bytes, string tempDocPath, string tempPdfPath)
{
try
{
string rs = RandomString(16, true);
tempDocPath = tempDocPath + rs + ".docx";
tempPdfPath = tempPdfPath + rs + ".pdf";
// This is where the problem happens with concurrent calls. I added
// the try catch when the file is in use to generate a new
// filename but the error still happens.
try
{
// Create a temp file
File.WriteAllBytes(tempDocPath, bytes);
}
catch (Exception Ex)
{
rs = RandomString(16, true);
tempDocPath = tempDocPath + rs + ".docx";
tempPdfPath = tempPdfPath + rs + ".pdf";
File.WriteAllBytes(tempDocPath, bytes);
}
word.Application app = new word.Application();
word.Document doc = app.Documents.Open(tempDocPath);
doc.SaveAs2(tempPdfPath, word.WdSaveFormat.wdFormatPDF);
doc.Close();
app.Quit(); // Clean up the word instance.
// Need the bytes to return the blob
byte[] pdfFileBytes = File.ReadAllBytes(tempPdfPath);
// Delete temp files
File.Delete(tempDocPath);
File.Delete(tempPdfPath);
// return blob
return Convert.ToBase64String(pdfFileBytes);
}
catch (Exception Ex)
{
throw Ex;
}
}
Client:
public async void btnConvert_Click(object sender, EventArgs e)
{
var response = await StartConvert();
foreach (SimpleResponse sr in response)
{
if (sr.Success)
{
byte[] bte = Convert.FromBase64String(sr.Result.ToString());
string rs = RandomString(16, true);
string pdfFileName = tempPdfPath + rs + ".pdf";
if (File.Exists(pdfFileName))
{
File.Delete(pdfFileName);
}
System.IO.File.WriteAllBytes(pdfFileName, bte);
}
else
{
}
}
}
private async Task<IEnumerable<SimpleResponse>> StartConvert()
{
var tasks = new List<Task<SimpleResponse>>();
foreach (string s in docPaths)
{
byte[] bte = File.ReadAllBytes(s);
tasks.Add(ConvertDocuments(Convert.ToBase64String(bte)));
}
return (await Task.WhenAll(tasks));
}
private async Task<SimpleResponse> ConvertDocuments(string requests)
{
using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
{
client.BaseAddress = new Uri(BaseApiUrl);
client.DefaultRequestHeaders.Add("Accept", "application/json");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//application/json
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, BaseApiUrl + ApiUrl);
var data = JsonConvert.SerializeObject(requests);
request.Content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response1 = await client.PostAsync(BaseApiUrl + ApiUrl, request.Content).ConfigureAwait(false);
var response = JsonConvert.DeserializeObject<SimpleResponse>(await response1.Content.ReadAsStringAsync());
return response;
}
}
Random String Generator
public string RandomString(int size, bool lowerCase = false)
{
var builder = new StringBuilder(size);
// Unicode/ASCII Letters are divided into two blocks
// (Letters 65–90 / 97–122):
// The first group containing the uppercase letters and
// the second group containing the lowercase.
// char is a single Unicode character
char offset = lowerCase ? 'a' : 'A';
const int lettersOffset = 26; // A...Z or a..z: length = 26
for (var i = 0; i < size; i++)
{
var #char = (char)_random.Next(offset, offset + lettersOffset);
builder.Append(#char);
}
return lowerCase ? builder.ToString().ToLower() : builder.ToString();
}
First, get rid of Task.Factory.StartNew ... t.Wait() - you don't need an additional task, the root level method is async and your blocking Wait just spoils the benefits of async by blocking synchronously.
Second, like a comment suggested above, the file name random string generator is most likely to be not really random. Either do not supply anything to the seed value of your pseudo-random gen, or use something like Environment.TickCount which should be sufficient for this. Guid.NewGuid() will work too.
Another good option for temp files is Path.GetTempFileName (also generates an empty file for you): https://learn.microsoft.com/en-us/dotnet/api/system.io.path.gettempfilename?view=netstandard-2.0
[HttpPost]
public async Task<SimpleResponse> Post([FromBody]string request)
{
var response = new SimpleResponse();
try
{
...
var result = await convert.CovertDocToPDF(...);
...
}
catch (Exception ex)
{
...
}
return response;
}
Based on your code it seems that you have a "faulty" random string generator for file name (I would say _random.Next is a suspect, possibly some locking and/or "app wide" instance could fix the issue). You can use Guid.NewGuid to create random part of file name (which in theory can have collisions also but in most practical cases should be fine) or Path.GetTempFileName:
var rs = Guid.NewGuid().ToString("N");
tempDocPath = tempDocPath + rs + ".docx";
tempPdfPath = tempPdfPath + rs + ".pdf";

Task executing a code 2 times instead of five

I have no idea why but my Task is executing a code only 2 times when i made 5 tasks to execute it.
for (int i = 0; i< 5; i++)
//MainUI
{
Task.Run(() =>
{
string s = Settings.ComboList[rnd.Next(Settings.ComboList.Count)];
string[] split = s.Split(":".ToCharArray());
string username = split[0];
string password = split[1];
twitch.GetOAuth(username, password, nesto, noCaptcha, proxyless, string.Empty);
Settings.ComboList.Remove(s);
});
}
public void GetOAuth(string Username, string Password, string Captchakey, bool noCaptcha, bool proxy, string proxyString)
//mainVoid
{
Console.WriteLine(noCaptcha);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://passport.twitch.tv/login");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
if (proxy == false)
{
string[] split = proxyString.Split(":".ToCharArray());
string proxyNum = split[0];
int port = int.Parse(split[1]);
httpWebRequest.Proxy = new WebProxy(proxyNum, port);
}
else
{
}
Console.WriteLine("Pred Captchu");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
if (noCaptcha == false)
{
Console.WriteLine("Captcha Solviong...");
CaptchaSolver client = new CaptchaSolver(Captchakey);
client.SolveRecaptchaV2("6Ld65QcTAAAAAMBbAE8dkJq4Wi4CsJy7flvKhYqX", "https://passport.twitch.tv/login", string.Empty, ProxyType.HTTP, out string captchaResult);
string json = "{\"username\":\"" + Username + "\",\"password\":\"" + Password + "\",\"client_id\":\"kimne78kx3ncx6brgo4mv6wki5h1ko\",\"undelete_user\":false,\"captcha\":{\"value\":\"" + captchaResult + "\",\"key\":\"6Ld65QcTAAAAAMBbAE8dkJq4Wi4CsJy7flvKhYqX\"}}";
streamWriter.Write(json);
}
else
{
string json = "{\"username\":\"" + Username + "\",\"password\":\"" + Password + "\",\"client_id\":\"kimne78kx3ncx6brgo4mv6wki5h1ko\",\"undelete_user\":false}";
streamWriter.Write(json);
}
}
Console.WriteLine("Finished");
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
string Code = TextParser.getBetween(result, "{\"access_token\":\"", "\"");
Console.WriteLine(Code);
bool getPrime = GetPrime(Code);
GetDetails(Code, getPrime, Username, Password);
}
}
Results I'm getting:
False
False
False
False
False
Pred Captchu
Pred Captchu
Pred Captchu
Pred Captchu
Pred Captchu
Captcha Solviong...
Captcha Solviong...
After it finished first 2 than it runs other 2 than the last one
Edit 1.
I checked again and all 5 task execute until this line where only 2 task execute.Every Task executes the line untill this one:
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))

How can I make this c# method multithreaded? [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 5 years ago.
Improve this question
I have this c# class that I am trying to make multi-threaded, or able to run 100 threads (requests?) at once.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] lines = File.ReadAllLines("C:\\checker/in.txt");
var accCount = File.ReadLines(#"C:\checker/in.txt").Count();
Console.Write("Accounts loaded: " + accCount);
Console.WriteLine();
foreach (string line in lines)
{
string[] account = line.Split(new char[] { ':' });
string user = account[0];
string pass = account[1];
addThreads(user, pass);
Threads.ForEach(t => t.Start());
Console.WriteLine();
}
// Suspend the screen.
Console.ReadLine();
}
public static List<Thread> Threads = new List<Thread>();
public static void addThreads(string user, string pass)
{
var checker = new Checker();
Threads.Clear();
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
}
}
public class Checker
{
//declare vars
string getUsername;
string getMember;
string getAuth;
string check;
public void checkAccount(string username, string password)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
byte[] data = Encoding.ASCII.GetBytes(
$"username={username}&password={password}&mod=www&ssl=1&dest=account_settings.ws");
WebRequest request = WebRequest.Create("https://secure.runescape.com/m=weblogin/login.ws");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string responseContent = null;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
//parse captcha
string patternCaptcha = #"Please\s*complete\s*the\s*reCAPTCHA\s*box";
string inputCaptcha = responseContent;
Match matchCaptcha = Regex.Match(inputCaptcha, patternCaptcha);
string captcha = matchCaptcha.Value;
if (captcha == "Please complete the reCAPTCHA box")
{
captcha = "true";
Console.Write("captcha,captcha,captcha,captcha");
Console.WriteLine();
//return "captcha,captcha,captcha,captcha";
}
else
{
//parse valid/invalid
string patternCheck = #"Your\s*login\s*or\s*password\s*was\s*incorrect";
string inputCheck = responseContent;
Match matchCheck = Regex.Match(inputCheck, patternCheck);
check = matchCheck.Value;
if (check == "Your login or password was incorrect")
{
check = "Invalid";
}
else
{
check = "Valid";
//parse display name
string pattern = #"(<span.*class=.header-top__name.>(.*?)</span>)";
string input = responseContent;
Match match = Regex.Match(input, pattern);
getUsername = match.Groups[2].Value;
byte[] bytes = Encoding.Default.GetBytes(getUsername);
getUsername = Encoding.UTF8.GetString(bytes);
getUsername = getUsername.Replace("?", " ");
//parse member status
string patternMember = #"(Currently\s*Not\s*a\s*Member)";
string inputMember = responseContent;
Match matchMember = Regex.Match(inputMember, patternMember);
getMember = matchMember.Value;
if (getMember == "Currently Not a Member")
{
getMember = "Non Member";
}
else
{
getMember = "Member";
}
//parse auth status
string patternAuthUrl = #"iframe src=\""(.*?)""";
string inputAuthUrl = responseContent;
Match matchAuthUrl = Regex.Match(inputAuthUrl, patternAuthUrl);
string getAuthUrl = matchAuthUrl.Groups[1].Value;
using (WebClient client = new WebClient())
{
string authSource = client.DownloadString(getAuthUrl);
string patternAuth = #"RuneScape\s*Authenticator\s*is\s*disabled";
string inputAuth = authSource;
Match matchAuth = Regex.Match(inputAuth, patternAuth);
getAuth = matchAuth.Value;
if (getAuth == "RuneScape Authenticator is disabled")
{
getAuth = "Auth Disabled";
}
else
{
getAuth = "Authed";
}
}
}
captcha = "false";
string curldata = getUsername + "," + getMember + "," + getAuth + "," + check;
Console.Write(curldata);
Console.WriteLine();
}
}
}
}
Instead of making my program check once per few seconds per post webrequest, how can I make this happen 50-100 times at the same time? Is this possible? Or do I need to do this a different way?
You need to avoid using threads as each thread uses in excess of 1MB of RAM and they are slow to create. You really want to use tasks (TPL) or observables (Rx).
In this case it is quite straight forward to use tasks.
Try this code:
string[] lines = File.ReadAllLines("C:\\checker/in.txt");
var accCount = lines.Count();
Console.Write("Accounts loaded: " + accCount);
Console.WriteLine();
var checker = new Checker();
var tasks =
from line in lines
let account = line.Split(new char[] { ':' })
let user = account[0]
let pass = account[0]
select Task.Factory.StartNew(() => checker.checkAccount(user, pass));
Task.WaitAll(tasks.ToArray());
Console.ReadLine();
That will read the text file and queue up a set of tasks to be run to check each line. The Task.WaitAll pauses the code until all of the tasks are completed.
This make efficient use of the thread-pool so that you're not wasting valuable resources starting up threads.
Your checkAccount is also not thread-safe at the moment. You need to move the field-level variables to be inside your method. It should look something like this:
public void checkAccount(string username, string password)
{
string getUsername;
string getMember;
string getAuth;
string check;
It's pretty simple first you need to do a method to call the threads
public void CallingThreadsMethod()
{
ThreadStart ts = new ThreadStart(SomeFunction);
Thread t = Thread(ts);
t.IsBackground = true;
t.Start();
}
void Somefunction(){}
or if you want many threads you can make a thread list
public static List<Thread> Threads = new List<Thread>();
public static void addThreads()
{
Threads.Clear();
Threads.Add(new Thread(Method1));
Threads.Add(new Thread(Method2));
}
And start it in you'r main function
Vars.addThreads();
Vars.Threads.ForEach(t => t.Start());
but if you're using windows forms or wpf i recommend using BackgroundWorkers

Categories