Hi all I have a client program about send and recieve file on LAN Network between 2 PC, but it get an error below: "Cross-thread operation not valid: Control 'Client' accessed from a thread other than the thread it was created on" in function SaveFile in line "if (saveFileDialog1.ShowDialog(this) == DialogResult.OK" So I need a help to fix it, Please help me, Thank very much.

It is source code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Threading;

#pragma warning disable

namespace GuiClient
{
    public partial class Client : Form
    {
        public delegate void UpdateListBoxCallBack(string s);
        public delegate void UpdateLabelCallBack(string s);
        private Stream stmReader = null;
        private NetworkStream nwkStream = null;
        private Stream stmWriter = null;
        private TcpClient tcpClient = null;
        SaveFileDialog saveFileDialog = new SaveFileDialog();
        public Client()
        {
            InitializeComponent();
        }
        private void Save(object sender, EventArgs e)
        {
           Thread t = new Thread(new ThreadStart(SaveFile));
            t.Start();
        }
        public void SaveFile()
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                txtFileName.Text = saveFileDialog1.FileName;
                set(null);
            }
            try
            {
                nwkStream = tcpClient.GetStream();
                stmReader = nwkStream;
                stmWriter = File.OpenWrite(txtFileName.Text);
                byte[] buff = new byte[1024];//1073741824
                int len = 0;
                set("Receiving");

                while ((len = stmReader.Read(buff, 0, 1024)) > 0)
                {
                    stmWriter.Write(buff, 0, len);
                    stmWriter.Flush();
                }
                set("File has received succesfully!");
            }
            catch (Exception ex) {
                MessageBox.Show(ex.ToString());
            }

            finally
            {
                nwkStream.Close();
                stmWriter.Close();
                stmReader.Close();
            }
        }

        public void Start(object sender, EventArgs e)
        {
            txtFileName.Clear();
            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ipserver.Text), int.Parse(port.Text));
            tcpClient = new TcpClient();
            tcpClient.Connect(ipe);
            StreamReader sr = new StreamReader(tcpClient.GetStream());
            StreamWriter sw = new StreamWriter(tcpClient.GetStream());
            string duongdan = sr.ReadLine() ;
            textBox1.Text = "Server send file : " + duongdan;
            saveFileDialog1.FileName = duongdan;
            saveFileDialog1.Title = "Save file from Server";
            saveFileDialog1.Filter = "Text Files (*.txt)|*.txt|Word Documents" + "(*.doc)|*.doc|All Files (*.*)|*.*";
            saveFileDialog1.ShowHelp = true;
        }
        void set(string s)
        {
            if (InvokeRequired)
            {
                object[] pList = { s };
                lblMessage.BeginInvoke(new UpdateListBoxCallBack(OnUpdateLabel), pList);
            }
            else
            {
                OnUpdateLabel(s);
            }
        }
        private void OnUpdateLabel(String s)
        {
            lblMessage.Text = s;
        }

        private void clearip(object sender, EventArgs e)
        {
            ipserver.Clear();
        }

        private void clearport(object sender, EventArgs e)
        {
            port.Clear();
        }

        private void clearfilename(object sender, EventArgs e)
        {
            txtFileName.Clear();
        }

        private void exit(object sender, EventArgs e)
        {
            Close();
        }

        private void disconectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            nwkStream.Close();
            stmWriter.Close();
            stmReader.Close();
        }

        private void Client_Load(object sender, EventArgs e)
        {

        }
    }
}

It is my project:
http://www.mediafire.com/?xprt10z40wrjvw7

Recommended Answers

All 8 Replies

You need to look into object locking, the error is caused by two threads accessing the same object at once. Locking will prevent this.

It isn't caused by deadlock, it's causes because only the UI thread can perform UI operations. In a Winforms application it is the main thread that is the UI thread. You start a thread and attempt to call ShowDialog in that thread. Doesn't work that way. Call UI stuff in the UI thread. Start your worker thread after you get the result from the dialog.

My bad skim reading code as was a dump of everything.

I haven't still understand, can you guide in a slow way and clear or evident ?

When you start your program it creates the main thread. In a Winforms program this is also known as the UI thread. You can only perform UI actions on the UI thread. In lines 30-34 you create a new thread to run the SaveFile method. The SaveFile method attepts to show a UI component (SaveFileDialog) but since it isn't the UI thread, you get a cross thread error.

What you should do is display the SaveFileDialog in the Save method, then start the SaveFile method (without the UI code).

Cheer thank for your opinion I will try now and who can't fix it for me ?

So what exactly code that I need to add and location to add it, please fix it for me, I can't do it myself. Thank very much for help.

So what exactly code that I need to add and location to add it, please fix it for me, I can't do it myself, I'm not good in programming. Thank very much for help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.