Как исправить отставание формы, когда его метки изменяются потоком? - PullRequest
1 голос
/ 26 января 2012

мое приложение отправляет файл на сервер, используя (socket tcp c #)
передача файла работает отлично ... но форма выполнения, которая показывает мне, что процесс отправки не работает хорошо
его отстает и показывает как 45 МБ /затем 2 Мбит / с он постоянно идет вверх и вниз, и когда я пытаюсь переместить окно, оно немного отстает, как будто что-то не так в потоке ... я надеюсь, вы понимаете, что происходит ..
как это исправить?

Thread thS = new Thread(timeElasped);
thS.Start();   //this code runs when the form show up

приведенный ниже код выполняется потоком в форме выполнения

    private void timeElasped()
    {
        int counter = 0;
        while (fileTransfer.busy)
        {
            rate = (fileTransfer.sum - prevSum);
            RateLabel(string.Format("{0}/Sec", CnvrtUnit(rate)));
            if(rate!=0)
                left = (fileTransfer.fileSize - fileTransfer.sum) / rate;
            prevSum = fileTransfer.sum;
            TimeSpan t = TimeSpan.FromSeconds(left);
            timeLeftLabel(FormatRemainingText(rate, t));
            TimeSpan Duration = TimeSpan.FromSeconds(counter);
            ElapsedLabel(string.Format("{0:D2}:{1:D2}:{2:D2}", Duration.Hours, Duration.Minutes, Duration.Seconds));
            counter++;
            Thread.Sleep(1000);
        }
    }

это код отправки файла

public static void sendFile(string filePath)
    {
        //initialize a thread for progress form
        Thread thFP = new Thread(fpRUN); 
        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        string fileName = Path.GetFileName(filePath);
        byte[] fileData;
        try
        {
            //sending file name and file size to the server
            busy = true;
            fileSize = fs.Length;
            byte[] fileDetial = null;
            string detail =  fileName + "," + fileSize.ToString();
            fileDetial = Encoding.ASCII.GetBytes(detail);
            client.Send(fileDetial);

            //sending file data to the server

            fileData = new byte[packetSize];
            count = 0;
            sum = 0;                          
            // running transfer rate
            fileProgress fP = new fileProgress("Sending...");
            //show the progress form
            thFP.Start(fP);

            while (sum < fileSize)
            {
                fP.ProgressBarFileHandler(sum, fileSize);
                fs.Seek(sum, SeekOrigin.Begin);
                fs.Read(fileData, 0, fileData.Length);
                count = client.Send(fileData, 0, fileData.Length, SocketFlags.None);
                sum += count;
            }
        }
        finally
        {
            busy = false;
            fs.Close();
            fileData = null;
            MessageBox.Show(string.Format("{0} sent successfully", fileName));
        }
    }

1 Ответ

0 голосов
/ 26 января 2012

Если ваша форма на какое-то время «заблокирована», вероятно, у вас плохой дизайн, поскольку ваш поток пользовательского интерфейса блокирует работу.

Вот простой, но полный пример рабочего потока иформа уведомления, обеспечивающая отзывчивость пользовательского интерфейса:

Форма:

public partial class Form1 : Form
{
    private Worker worker;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        worker = new Worker();
        worker.ProgressUpdated += this.worker_ProgressUpdated;
        worker.WorkDone += this.worker_WorkDone;
        worker.Start();
    }

    private void worker_WorkDone(object sender, EventArgs e)
    {
        // Detaches event handlers
        // /!\ Will be called from a thread different than the UI thread
        worker.ProgressUpdated -= this.worker_ProgressUpdated;
        worker.WorkDone -= this.worker_WorkDone;
    }

    private void worker_ProgressUpdated(object sender, ProgressEventArgs e)
    {
        // Updates the UI
        // /!\ Will be called from a thread different than the UI thread
        this.SetLabelText(string.Format("Percentage: {0}", ((double)e.Value * 100 / (e.Max - e.Min))));
    }

    private void SetLabelText(string text)
    {
        // Following required if the method is called from a thread that is not the UI thread
        if (this.label1.InvokeRequired)
        {
            this.label1.Invoke(new MethodInvoker(() => this.SetLabelText(text)));
        }
        else
        {
            this.label1.Text = text;
        }
    }
}

Рабочий класс:

public class ProgressEventArgs : EventArgs
{
    public int Value { get; set; }

    public int Max { get; set; }

    public int Min { get; set; }
}

public class Worker
{
    public delegate void ProgressUpdatedEventHandler(object sender, ProgressEventArgs e);

    public event ProgressUpdatedEventHandler ProgressUpdated;

    public event EventHandler WorkDone;

    public void Start()
    {
        Thread workerThread = new Thread(new ThreadStart(this.DoWork));
        workerThread.Start();
    }

    private void DoWork()
    {
        int min = 0;
        int max = 1000000;

        for (int i = min; i < max; i++)
        {
            // Simulates work
            ////System.Threading.Thread.Sleep(1);

            // Notify of progress update
            ////this.OnProgressUpdate(min, max, i);

            // Notify of progress update but not every time to save CPU time
            // Uses mod function to do the job 1 out of 100 times
            if (i % 100 == 0)
            {
                this.OnProgressUpdate(min, max, i);
            }
        }

        // Notify the work is done
        if (this.WorkDone != null)
        {
            this.WorkDone(this, EventArgs.Empty);
        }
    }

    private void OnProgressUpdate(int min, int max, int value)
    {
        if (this.ProgressUpdated != null)
        {
            this.ProgressUpdated(this, new ProgressEventArgs { Max = max, Min = min, Value = value });
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...