Описание проблемы: при нескольких аккаунтах берет один и тот же аккаунт, хотя так быть не должно. Код: public string[] accounts; private async void threadAsync() { var accs = new List<string>(accounts); while (accs.Count!= 0) { string acc = accounts[0]; accs.RemoveAt(0); try { string subs = await GetAuthAsync(acc); richTextBox1.AppendText($" Account:{acc}, subs:{subs}"); } catch(Exception ex) { MessageBox.Show($"Ошибка: -- {ex}"); } } } private async void button1_Click(object sender, EventArgs e) { accounts = textBox2.Text.Split('\n'); int proces_count = Convert.ToInt32(textBox1.Text); for(int i = 0; i < proces_count; i++) { Thread t = new Thread(new ThreadStart(threadAsync)); // Start ThreadProc. Note that on a uniprocessor, the new // thread does not get any processor time until the main thread // is preempted or yields. Uncomment the Thread.Sleep that // follows t.Start() to see the difference. t.Start(); } Код public string[] accounts; private async void threadAsync() { var accs = new List<string>(accounts); while (accs.Count!= 0) { string acc = accounts[0]; accs.RemoveAt(0); try { string subs = await GetAuthAsync(acc); richTextBox1.AppendText($" Account:{acc}, subs:{subs}"); } catch(Exception ex) { MessageBox.Show($"Ошибка: -- {ex}"); } } } private async void button1_Click(object sender, EventArgs e) { accounts = textBox2.Text.Split('\n'); int proces_count = Convert.ToInt32(textBox1.Text); for(int i = 0; i < proces_count; i++) { Thread t = new Thread(new ThreadStart(threadAsync)); // Start ThreadProc. Note that on a uniprocessor, the new // thread does not get any processor time until the main thread // is preempted or yields. Uncomment the Thread.Sleep that // follows t.Start() to see the difference. t.Start(); }
Блять ну нахуя делать через while когда существуют foreach? Прочитал файл, разбил на строки и ебашишь массив через foreach --- Сообщение объединено с предыдущим 31 авг 2021 string[] lines = File.ReadAllLines("test.txt"); foreach (string line in lines) { // что-нибудь делаем с прочитанной строкой line } C# string[] lines = File.ReadAllLines("test.txt"); foreach (string line in lines) { // что-нибудь делаем с прочитанной строкой line }
throwyourfears, читай тему, у него несколько потоков, разные потоки берут один и тот же элемент массива, для того чтобы этого избежать он удаляет первый элемент, чтобы другой поток взял уже другой элемент массива
throwyourfears, я понял к чему клонишь. Ты хочешь, чтобы он внутри цикла вызывал асинхронный метод с параметром. Ну пускай пробует.
Во первых скорее всего ты через другой поток не достучишься до элементов управления в главном потоке - можно использовать invoke, во вторых ты присваиваешь в массив accounts что то перед новым потоком, в новом потоке потоке ты берешь в переменную acc первый элемент из массива accounts, разве у тебя не должен результат быть каждый раз один
TheWall_inactive2650523, public string[] accounts; List<string> accs; private async void threadAsync() { while (accs.Count!= 0) { string account = accounts[0]; accs.RemoveAt(0); try { string subs = await GetAuthAsync(account); richTextBox1.AppendText($" Account:{account}, subs:{subs}"); } catch(Exception ex) { MessageBox.Show($"Ошибка: -- {ex}"); } } } private async void button1_Click(object sender, EventArgs e) { accounts = textBox2.Text.Split('\n'); accs = new List<string>(accounts); int proces_count = Convert.ToInt32(textBox1.Text); for (int i = 0; i < proces_count; i++) { Thread t = new Thread(new ThreadStart(threadAsync)); // Start ThreadProc. Note that on a uniprocessor, the new // thread does not get any processor time until the main thread // is preempted or yields. Uncomment the Thread.Sleep that // follows t.Start() to see the difference. t.Start(); } // Start ThreadProc. Note that on a uniprocessor, the new // thread does not get any processor time until the main thread // is preempted or yields. Uncomment the Thread.Sleep that // follows t.Start() to see the difference. ////foreach (var accs in accounts) ////{ //// string email = accs.Split(':')[0]; //// string pass = accs.Split(':')[1]; //// string subs = await GetAuthAsync($"{email}:{pass}"); //// richTextBox1.AppendText($" Account:{accs}, subs:{subs}"); ////} } чего то не получается(( Код public string[] accounts; List<string> accs; private async void threadAsync() { while (accs.Count!= 0) { string account = accounts[0]; accs.RemoveAt(0); try { string subs = await GetAuthAsync(account); richTextBox1.AppendText($" Account:{account}, subs:{subs}"); } catch(Exception ex) { MessageBox.Show($"Ошибка: -- {ex}"); } } } private async void button1_Click(object sender, EventArgs e) { accounts = textBox2.Text.Split('\n'); accs = new List<string>(accounts); int proces_count = Convert.ToInt32(textBox1.Text); for (int i = 0; i < proces_count; i++) { Thread t = new Thread(new ThreadStart(threadAsync)); // Start ThreadProc. Note that on a uniprocessor, the new // thread does not get any processor time until the main thread // is preempted or yields. Uncomment the Thread.Sleep that // follows t.Start() to see the difference. t.Start(); } // Start ThreadProc. Note that on a uniprocessor, the new // thread does not get any processor time until the main thread // is preempted or yields. Uncomment the Thread.Sleep that // follows t.Start() to see the difference. ////foreach (var accs in accounts) ////{ //// string email = accs.Split(':')[0]; //// string pass = accs.Split(':')[1]; //// string subs = await GetAuthAsync($"{email}:{pass}"); //// richTextBox1.AppendText($" Account:{accs}, subs:{subs}"); ////} } чего то не получается((
Вот именно. Если ты питонист, то тебя говной воняет, через форум чувствую. Рассказываю как определить питониста в данном разделе да и на форумах. По ключевым словам, ебаный шашлык. Любой питонист употребляет "мульти", в данном случаи "мультипоточность". В сишарпе нету такого понятия, в C# есть понятие МНОГОПОТОЧНОСТЬ. МУЛЬТИПОТОЧНОСТЬ - ЭТО ТАМ, В КРУЖКЕ ЮНЫХ ДОЛБОЁБОВ. Сейчас бы while в таких случаях использовать, да ты бы ещё винапи подкрутил, ахуеть ты потоки ловко запускаешь, а даже сначала этого не понял, МОЛОДЕДЦ. Питонистам сами знаете где место
@CoderVir, почему то в данном случаи хочется только напеть песенку- охуели, бабы охуели. Нету сил моих.
@CoderVir, да я малым был(хотя и щас мне 15), когда питон изучать начал, щас понимаю, что уходить нужно
Pashok576, чувак, это маркетинговый ход. А по сути кидалово, расчитаное на дядичек 30+. А если ты хочешь чему то обучится и у тебя есть стремление, то тебе курсы нахуй не нужны. Задача курсов в этом плане- научить учится и всё, поднести основы. А основы все в интернете, ютюбе. Дальше после того как изучил основы, начинаешь изучать определённые библиотеки, ну допустим написание ботов telegram.bot(в C# тоже есть). Ну и всё, получилось пару ботов и идешь делать деньги.
Навоняли тут горе-кодеры выше, но практически ничего дельного так и не смогли сказать. А разговоров-то устроили.., печально) Спойлер public string[] accounts; public List<string> accs; private async void threadAsync() { while (accs.Count!= 0) { var account = string.Empty; lock(accs) { account = accs[0]; accs.RemoveAt(0); } try { string subs = await GetAuthAsync(account); richTextBox1.AppendText($" Account:{account}, subs:{subs}"); } catch(Exception ex) { MessageBox.Show($"Ошибка: -- {ex}"); } } } private async void button1_Click(object sender, EventArgs e) { accounts = textBox2.Text.Split('\n'); accs = new List<string>(accounts); int proces_count = Convert.ToInt32(textBox1.Text); for (int i = 0; i < proces_count; i++) { Thread t = new Thread(new ThreadStart(threadAsync)); t.Start(); } } Код public string[] accounts; public List<string> accs; private async void threadAsync() { while (accs.Count!= 0) { var account = string.Empty; lock(accs) { account = accs[0]; accs.RemoveAt(0); } try { string subs = await GetAuthAsync(account); richTextBox1.AppendText($" Account:{account}, subs:{subs}"); } catch(Exception ex) { MessageBox.Show($"Ошибка: -- {ex}"); } } } private async void button1_Click(object sender, EventArgs e) { accounts = textBox2.Text.Split('\n'); accs = new List<string>(accounts); int proces_count = Convert.ToInt32(textBox1.Text); for (int i = 0; i < proces_count; i++) { Thread t = new Thread(new ThreadStart(threadAsync)); t.Start(); } } Подробней тут: https://metanit.com/sharp/tutorial/11.4.php