RE: Create Form from Async-Callback
- From: Roemer <Roemer@xxxxxxxxxxxxxxxx>
- Date: Fri, 10 Mar 2006 05:21:27 -0800
Thanks, I'll have a look at the Cassini Sample Web Server.
The Problem with your code in the post before was, that, le'ts say, every
Client that connects would open a Form. So that means there could be
unlimited Forms so I need do genereate them when a Client connects.
I by now found a little Workaround which looks like:
/************ CODE ************/
using System;
using System.Net.Sockets;
using System.Net;
using System.Windows.Forms;
using System.Threading;
class Program {
static SynchronizationContext ctx;
static void Main(string[] args) {
Control ctl = new Control();
ctx = SynchronizationContext.Current;
StartListening();
Application.Run();
}
static void StartListening() {
TcpListener m_tcpListener = new TcpListener(IPAddress.Any, 1234);
m_tcpListener.Start();
m_tcpListener.BeginAcceptTcpClient(new
AsyncCallback(AcceptTcpClientCallback), m_tcpListener);
}
private static void AcceptTcpClientCallback(IAsyncResult ar) {
TcpListener listener = (TcpListener)ar.AsyncState;
TcpClient client = listener.EndAcceptTcpClient(ar);
listener.BeginAcceptTcpClient(new
AsyncCallback(AcceptTcpClientCallback), listener);
// This Method has to run in the "Main Thread", where
Application.Run() was fired
Program.ctx.Send(new SendOrPostCallback(CreateForm), null);
}
static void CreateForm(object o) {
Form myForm = new Form();
myForm.Show();
}
}
/************ END CODE ************/
Well, the most important part is that I added an SynchronizationContext
which I set on the Main Thread and then run the CreateForm on that Context
(ctx.Send()). So this solution is working so far but has something that
annoys me:
The first Line in the Main() is a
Control ctl = new Control();
Without this line, the SynchronizationContext.Current would be null so I
can't Send something to it.
I looked around in Reflector and found in the Constructor of a Control the
Line:
WindowsFormsSynchronizationContext.InstallIfNeeded();
Most of what's going on in this Function is Internal so I can't just call it
in my Programm.
So I guess I have to life with that.
So, do you think that this solution with the SynchronizationContext and it's
Send and the dummy Control is ok and solid?
Thanks!
//Roman
.
- Follow-Ups:
- RE: Create Form from Async-Callback
- From: "Wei-Dong XU [MSFT]"
- RE: Create Form from Async-Callback
- References:
- Create Form from Async-Callback
- From: Roemer
- RE: Create Form from Async-Callback
- From: "Wei-Dong XU [MSFT]"
- RE: Create Form from Async-Callback
- From: "Wei-Dong XU [MSFT]"
- RE: Create Form from Async-Callback
- From: "Wei-Dong XU [MSFT]"
- Create Form from Async-Callback
- Prev by Date: Re: Structures vs. Classes
- Next by Date: Re: IndexOf on bound ComboBox not working??
- Previous by thread: RE: Create Form from Async-Callback
- Next by thread: RE: Create Form from Async-Callback
- Index(es):
Relevant Pages
|