Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Sharing resources between threads (ListBox)

shared resources; threads;

This topic has been archived. This means that you cannot reply to this topic.
No replies to this topic

#1 FrancoAti

FrancoAti

    CC Regular

  • Member
  • PipPipPip
  • 32 posts

Posted 23 May 2015 - 02:06 PM

Whatsupp guys,a have a tcp server and when it receive a message from any client connected he should add a TextBlock in a ListBox but i receive the following error message:

 

The calling thread cannot access this object because a different thread owns it.

 

When i will change a text block status information and when i add any item in the list box.

The following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ServerChat
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        [STAThread]
        private void escuta()
        {

            try
            {
                Socket sd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 555);

                sd.Bind(ipe);

                sd.Listen(2);

                Socket txrx = sd.Accept();

                lock (status) {
                    status.Text = "Conectado a " + txrx.RemoteEndPoint.ToString();
                }
                

                while (true)
                {
                    byte[] buffer = new byte[1000];

                    txrx.Receive(buffer);

                    lock(Conversa){
                        Conversa.Items.Add(Encoding.ASCII.GetString(buffer));
                    }

                    
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
            }

        }

        
        public MainWindow()
        {
            InitializeComponent();
            
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            new Thread(escuta).Start();
        }

    }
}

I know that theres a problem in WPF forms and access on it from threads,but i dont now how solve this.






Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download