Регистрация Главная Сообщество
Сообщения за день Справка Регистрация

Фоновое выполнение действия

-

Вопросы и ответы, обсуждения

- Ваши вопросы по C# только в данном разделе

Ответ
 
Опции темы
Старый 10.10.2012, 17:17   #16
 Разведчик
Аватар для sith999
 
sith999 на правильном пути
Регистрация: 07.09.2010
Сообщений: 44
Популярность: 92
Сказал(а) спасибо: 15
Поблагодарили 23 раз(а) в 6 сообщениях
 
По умолчанию Re: Фоновое выполнение действия

У меня не получается то,что задумано.
Мне нужно,что бы считывалось с richtextBox информация и с ней уже делались операции.
Вот пример(пример приведу на программе для тюряги):

Код:
string[] lines = richTextBox1.Lines;
            for (int i = 0; i < lines.Length; i++)
            {
                string[] idauth = lines[i].Split(';');
                string id = idauth[0];
                if (idauth[0] != "")
                {
                    string auth = idauth[1];
                    string text = this.post("http://109.234.157.91/prison/universal.php?sendPresent", "method=sendPresent&user=" + id + "&key=" + auth + "&recipients=" + textBox1.Text + "&present_id=" + b);
                }
                else
                {
                    break;
                }

            }
Но как бы я не старался(разными способами пробывал в BackgroundWorker) он всё равно ругается.
Вот пример ошибки
Код:
Недопустимая операция в нескольких потоках: попытка доступа к элементу управления 'richTextBox1' не из того потока, в котором он был создан.


Вот по какому примеру я последнее пытался сделать:

Код:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
            private int numberToCompute = 0;
            private int highestPercentageReached = 0;

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // Get the BackgroundWorker that raised this event.
            BackgroundWorker worker = sender as BackgroundWorker;

            // Assign the result of the computation
            // to the Result property of the DoWorkEventArgs
            // object. This is will be available to the 
            // RunWorkerCompleted eventhandler.
            e.Result = ComputeFibonacci((int)e.Argument, worker, e);
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // First, handle the case where an exception was thrown.
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
                // Next, handle the case where the user canceled 
                // the operation.
                // Note that due to a race condition in 
                // the DoWork event handler, the Cancelled
                // flag may not have been set, even though
                // CancelAsync was called.
                resultLabel.Text = "Canceled";
            }
            else
            {
                // Finally, handle the case where the operation 
                // succeeded.
                resultLabel.Text = e.Result.ToString();
            }

            // Enable the UpDown control.
            this.numericUpDown1.Enabled = true;

            // Enable the Start button.
            startAsyncButton.Enabled = true;

            // Disable the Cancel button.
            cancelAsyncButton.Enabled = false;
        }

        long ComputeFibonacci(int n, BackgroundWorker worker, DoWorkEventArgs e)
        {
            // The parameter n must be >= 0 and <= 91.
            // Fib(n), with n > 91, overflows a long.
            if ((n < 0) || (n > 91))
            {
                throw new ArgumentException(
                    "value must be >= 0 and <= 91", "n");
            }

            long result = 0;

            // Abort the operation if the user has canceled.
            // Note that a call to CancelAsync may have set 
            // CancellationPending to true just after the
            // last invocation of this method exits, so this 
            // code will not have the opportunity to set the 
            // DoWorkEventArgs.Cancel flag to true. This means
            // that RunWorkerCompletedEventArgs.Cancelled will
            // not be set to true in your RunWorkerCompleted
            // event handler. This is a race condition.

            if (worker.CancellationPending)
            {
                e.Cancel = true;
            }
            else
            {
                if (n < 2)
                {
                    result = 1;
                }
                else
                {
                    result = ComputeFibonacci(n - 1, worker, e) +
                             ComputeFibonacci(n - 2, worker, e);
                }

                // Report progress as a percentage of the total task.
                int percentComplete =
                    (int)((float)n / (float)numberToCompute * 100);
                if (percentComplete > highestPercentageReached)
                {
                    highestPercentageReached = percentComplete;
                    worker.ReportProgress(percentComplete);
                }
            }

            return result;
        }

        private void startAsyncButton_Click(object sender, EventArgs e)
        {
            resultLabel.Text = String.Empty;

            // Disable the UpDown control until 
            // the asynchronous operation is done.
            this.numericUpDown1.Enabled = false;

            // Disable the Start button until 
            // the asynchronous operation is done.
            this.startAsyncButton.Enabled = false;

            // Enable the Cancel button while 
            // the asynchronous operation runs.
            this.cancelAsyncButton.Enabled = true;

            // Get the value from the UpDown control.
            numberToCompute = (int)numericUpDown1.Value;

            // Reset the variable for percentage tracking.
            highestPercentageReached = 0;

            // Start the asynchronous operation.
            backgroundWorker1.RunWorkerAsync(numberToCompute);
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
        }

        private void cancelAsyncButton_Click(object sender, EventArgs e)
        {
            // Cancel the asynchronous operation.
            this.backgroundWorker1.CancelAsync();

            // Disable the Cancel button.
            cancelAsyncButton.Enabled = false;
        }
    }
}
  Ответить с цитированием
Ответ


Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.

Быстрый переход

Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Фоновое меню [Pacman] Etty Прочий софт для Counter-Strike 4 26.07.2012 22:39
[Программа] выполнение срочняков maniakk Тюряга ВКонтакте 58 07.05.2012 13:55
[Помогите!] выполнение замутов Женёк777 Общение и обсуждение (Тюряга ВК) 6 20.06.2011 01:48

Заявление об ответственности / Список мошенников

Часовой пояс GMT +4, время: 06:30.

Пишите нам: [email protected]
Copyright © 2024 vBulletin Solutions, Inc.
Translate: zCarot. Webdesign by DevArt (Fox)
G-gaMe! Team production | Since 2008
Hosted by GShost.net