-
October 4th, 2010, 08:21 PM
#1
form controll threading
I realise this topic has been covered before,
but i am struggling to grasp the concept of delegates and stuff.
my program has a multi lines textbox, and a function (which runs on a different thread) that runs in a loop continuesly receiving data from a socket. this data comes in the form of a string, and it is made into a system.string, and is then appended to the textbox
the problem i am having is that the textbox is created on thread1, where has the function is on thread2. trying to access the textbox from thread 2 makes baby jesus cry. I understand that this is where i need to use the invoke methods, and delegate functions, but as to implimenting these processing to solve my delema is still beyond my grasp.
i can show you what i have so far in terms of relevant code
public ref class Form1 : public System::Windows::Forms::Form
{
public:
delegate void OutPutBoxAppend(System::String^ ms);
OutPutBoxAppend^ myDelegate;
Form1(void)
{
CONNECTED = false;
connectSockets();
myDelegate = gcnew OutPutBoxAppend(this, &Form1::OutPutBoxWork);
Application::Run(gcnew loginForm(commandSocket));
InitializeComponent();
Sleep(10);
Thread^ oThread = gcnew Thread(gcnew ParameterizedThreadStart(Form1::ThreadProc1));
oThread->Start(this);
//
//TODO: Add the constructor code here
//
}
void OutPutBoxWork(System::String^ ms)
{
this->ouputBox->AppendText(ms);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////--code gap
static void ThreadProc1(System::Object ^obj)
{
Form1^ ob = (Form1^) obj;
for(;; )
{
string recvStr;
if((recvStr = ob->recvData(ob->getMonSocket())) == "")
{
MessageBox::Show(L"could not receive stream");
break;
}else{
using namespace System::Runtime::InteropServices;
recvStr.append("\r\n");
System::String^ ms;
ms = Marshal::PtrToStringAnsi(static_cast<IntPtr>(const_cast<char *>(recvStr.c_str())));
if(ob->ouputBox->InvokeRequired)
{
OutPutBoxAppend ^d = gcnew OutPutBoxAppend(^ms);
ob->Invoke(ob->myDelegate);
}else{
ob->ouputBox->AppendText(ms);
}
}
}
}
Edit: This obviously doesnt build, i was trying to addapt one of the examples givin on the msdn website.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|