Модераторы: gambit, Partizan
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Блокировка GUI? обновление элемента формы блокирует ее:( 
V
    Опции темы
Yevhen
Дата 16.7.2007, 13:05 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 2
Регистрация: 16.7.2007

Репутация: нет
Всего: нет



 smile 
Здрасте,
я уже в отчаяни, трети сутки сижу с этой проблемой...  smile 
Может кто по опытней меня и сталкивался с чем-то подобным?
Есть такой простенький код:

Код

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;

namespace WindowsApplication2
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Server server = new Server("Server");
            Thread serverThread = new Thread(new ThreadStart(Server.startServer));
            serverThread.Start();
            Application.Run(new Form1());
        }
    }
}



using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Collections;
using System.Runtime.Serialization.Formatters;

namespace WindowsApplication2
{
    class Server
    {
        private static string name;
        public Server()
        {
        }
        public Server(string name)
        {
            Server.name = name;
        }
        public static void startServer()
        {
            System.Console.WriteLine("Server");
            BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
            BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
            serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
            IDictionary p = new Hashtable();
            p["port"] = 4000;
            p["name"] = "RemoteServer";
            ChannelServices.RegisterChannel(new TcpChannel(p, clientProvider, serverProvider));
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(ServerObject), Server.name, WellKnownObjectMode.Singleton);
            while (true)
            {
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsApplication2
{
    public class ServerObject : MarshalByRefObject, IServer
    {
        public event NotifyEventHandler NotifyEvent;

        public void Notify(string message)
        {
            if (NotifyEvent != null)
                NotifyEvent(this, new NotifyEventArgs(message));
        }
    }
}


using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsApplication2
{
    public delegate void NotifyEventHandler(object sender, NotifyEventArgs e);

    public interface IServer
    {
        event NotifyEventHandler NotifyEvent;
        void Notify(string message);
    }
}


using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsApplication2
{
    [Serializable]
    public class NotifyEventArgs : EventArgs
    {
        private string _message;

        public string Message
        {
            get { return _message; }
        }

        public NotifyEventArgs(string message)
        {
            _message = message;
        }
    }
}


using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsApplication2
{
    public interface IForm
    {
        void setStatus(string messedge);
    }
}


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Collections;
using System.Runtime.Serialization.Formatters;

namespace WindowsApplication2
{
    public partial class Form1 : Form,IForm
    {
        private IServer server;
        private IClient client;
        
        public Form1()
        {
            InitializeComponent();
            BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
            BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
            serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
            IDictionary p = new Hashtable();
            p["port"] = 0;
            p["name"] = "RemoteClient";
            ChannelServices.RegisterChannel(new TcpChannel(p, clientProvider, serverProvider));
            server = (IServer)Activator.GetObject(typeof(IServer), "tcp://localhost:4000/Server");
            client = new ClientObject(server, this);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.server.Notify(this.label1.Text + " a");
        }
        public void setStatus(string messege)
        {
            this.label1.Text = messege;
        }


    }
}



using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsApplication2
{
    public interface IClient
    {
        void NotifyEventMethod(object sender, NotifyEventArgs e);
    }
}


using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsApplication2
{
    public class ClientObject : MarshalByRefObject, IClient
    {
        private IServer _server;
        private IForm _f;
        


        public ClientObject(IServer server, Form1 form)
        //public ClientObject(IServer server)
        {
            _server = server;
            _f = form;
            _server.NotifyEvent += new NotifyEventHandler(NotifyEventMethod);
        }

        ~ClientObject()
        {
            _server.NotifyEvent -= new NotifyEventHandler(NotifyEventMethod);
        }

        public void NotifyEventMethod(object sender, NotifyEventArgs e)
        {
            Console.WriteLine("##########" + e.Message);
            this._f.setStatus(e.Message);
            Console.WriteLine("##########" + e.Message);
        }
    }
}



значит проблема в следующем, когда я пытаюсь выполнить this._f.setStatus(e.Message); программа перестает реагировать на внешние раздрожители, т.е. при обновлении label1  smile 

если же this._f.setStatus(e.Message);  вобще убрть/закоментировать, то прога работает! Так что думаю проблемма лежит и менно в Форме...

Зарание спасибо...
PM MAIL   Вверх
mr.DUDA
Дата 16.7.2007, 23:02 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


3D-маньяк
****


Профиль
Группа: Экс. модератор
Сообщений: 8244
Регистрация: 27.7.2003
Где: город-герой Минск

Репутация: 24
Всего: 232



Попробуйте юзать this.Invoke и делегат, вместо того чтобы ставить setStatus напрямую. Походу, проблема с потоками.


--------------------
user posted image
PM MAIL WWW   Вверх
Yevhen
Дата 24.7.2007, 11:58 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 2
Регистрация: 16.7.2007

Репутация: нет
Всего: нет



Спасибо!
Действительно проблемма была здесь!
Еще раз большое спасибо...........
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Прежде чем создать тему, посмотрите сюда:
mr.DUDA
THandle

Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс "транслит" если у Вас нет русских шрифтов.
Что делать если Вам помогли, но отблагодарить помощника плюсом в репутацию Вы не можете(не хватает сообщений)? Пишите сюда, или отправляйте репорт. Поставим :)
Так же не забывайте отмечать свой вопрос решенным, если он таковым является :)


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, mr.DUDA, THandle.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Разработка Windows Forms | Следующая тема »


 




[ Время генерации скрипта: 0.0440 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.