Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a question regarding a TCP Connection Class I'm writing.
The Connection Class I already wrote can establish a connection via TCP. It listens and writes to that connection from two different threads. Now I want to improve that class.
I want to establish this connection fully asynchronous so that the connection can be establishes while other things in my application will be prepared.
But I have some other Classes which needs an established connection to work properly. So, my question is, could someone explain me with an little example how I could establish the connection asynchronous with the possibility that an other class starts to work after the connection is established?
My first idea was to fire an event after the TCP Client is connected but then I got in trouble with the fact, that the connection is only fully established if the remote server sends a message back.
After that I got an idea to create a connection state. But now I don't know how to proceed further.
If it's not the way how to use await and async please let me know.
Thanks in advance,
Patrick
Edit:
Thanks for your answers. To clarify things I want to update my post.
As someone requested what I have so far, I posted my source code at GitHub. In Line 46 I set the connection state to Connecting. After the TCP connection is established I change the status to Fetching (L155). Now I have to wait for the message which indicates that the connection is fully ready. After the Message came I expected I set the State to Open (L315) and fire an ConnectionEstablished Event.
Please excuse but I can't post more than 2 links.
My bit into this: instead of using thread blocks; write a Task for the TCP connection with ManualresetEvent. Making the other part of Thread to change their state based on ManualresetEvent. I personally like Task link is -> https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx
over Thread or Threadpool.
Edit: I have written this on notepad today. If it gives any help.
Task t = Task.Run(() =>
{
//do the connection thing
Connection();
connectionDone.Set(); //Manualeventreset connectionDone = new ManualResetEvent(false);
});
try
{
t.Wait();
}
catch (AggregateException ae)
{
//write the exception somewhere
WriteLog("Exception in task: " + ae);
}
finally
{
connectionDone.Reset();
}
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm working with Anonymous Pipes to be able to communicate between 2 applications. I have 3 classes. A base class Node which holds the incoming and outgoing streams and methods like Read and Write. Deriving from this class are Client and Server. They each initialize respectively their AnonymousPipeClientStream and AnonymousPipeServerStream and have a method to sync with each other.
Having above code allows me to communicate between the 2 applications. I start the "server" application. This application starts the "client".
When both applications are started I need to send some arguments from the server to the client. The client is basically waiting for messages from the server. On the server I need to start the reading of the arguments on the client, then send the arguments and end the reading on the client so it's free to start another task. To do this I simply need to
write the start command,
write the arguments,
write the end command and
wait for the client to confirm the task is finished.
public void ServerStartClientTask()
{
Write(ReadInputs); // (1)
Write(Arg1); // (2)
Write(Arg2); // (2)
Write(ReadInputs); // (3)
while (WaitFor(ReadInputs)); // (4)
}
This is "straightforward" when you're the writer of the code (in my opinion) and is the convention how communication with the client has to happen. I wanted to make it more clear for myself and my colleagues so I came up with the following:
public void StartClientTask(Flag flag)
{
Write(flag);
}
public void EndClientTask(Flag flag)
{
Write(flag);
while (WaitFor(flag)) { }
}
public void ServerStartClientTask()
{
StartClientTask(ReadInputs); // (1)
Write(Arg1); // (2)
Write(Arg2); // (2)
EndClientTask(ReadInputs); // (3) and (4)
}
This code merely wraps code into another method to make it more readable how the communication is dome with the client.
Now for the question.
This example is not limiting to my question but just the use case I have now and to introduce my question. Is doing this wrapping of code with just other names a good or bad practice? Both examples work perfectly fine, they're just written differently. Is there a benefit to doing the 2nd approuch or would you rather just write a comment at (1), (3) and (4) in the 1st example?
In my opinion this is a very good practice and I use it all the time.
Makes the code very readable for other developers.
this way I rarely have to use comments inside my methods because the names of the methods explain what is happening.
This question already has answers here:
Listening for an Ethernet Cable Unplugging Event for a TCP Server Application
(4 answers)
Closed 5 years ago.
I have an application with one server and one client.
How the client will know if the server cable is unplugged or disconnect? Is there event for that?
I don’t want to set a timer to check occasionally if the server gets messages…
And i don't want to use poll...
Thanks,
Elad
Refer at that questions :
Stack overflow 1
StackOverflow 2
Yopu have to analyze the connection status in all the phases and understand in wich phase are the problem, anyway why the connection doesn't works.
There are also other link that refer to your question :
Stack overflow 3
Blog
Last method, work with NetworkChange.NetworkAvailabilityChanged Event
Link : enter link description here
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have two questions about use sql server 2008 in c#.
questions 1 : What is the number of simultaneous query for a connection sql server 2005 in c#?
my connection string is :
Data Source = localhost;database=TaskQueue;Persist Security Info=True;integrated security=SSPI; MultipleActiveResultSets=true; Connection Timeout=0;Pooling=false;
questions 2 : what is Productive lifetime of a connection ? i want to keep open a global connection in the end off runing app and just use for this connection.
Do problems occur with this method?
What is the number of simultaneous query for a connection sql server 2005 in c#?
SQL Server 2005 Standard Edition can support a maximum of 32,767 simultaneous connections.
What is Productive lifetime of a connection ? i want to keep open a global connection in the end off runing app and just use for this connection. Do problems occur with this method?
SQL Server takes advantage of connection pooling and as such you'll generally want to keep your connections as short-lived as opposed so that they can be returned to the pool after use.
So consider wrapping your SQL calls within a using statement to ensure they are opened, executed, and properly disposed of as opposed to using a global connection that stays open:
using (var connection = new SqlConnection("your-connection-string"))
{
// Do stuff
}
Check Your Connection String
It's worth noting that your existing connection string has pooling explicitly disabled, which won't allow you to take advantage of the built-in connection pooling:
Data Source = ...; Pooling=false;
I'd highly recommend turning this back on unless you absolutely know what you are doing, as otherwise you might experience some unexpected behaviors, orphaned connections, etc.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am building an MVC app and in this appllication there are actions that implies some things. So we wish to warn our customers / users using mailing system. I'm building both a local application and a web store, so I'll need to send a lot of mails sometimes.
I am currently using MvcMailer why does nicely its job, but my main concern is that since it occurs during a normal method call (ex: result of an operation, then:
MvcMailMessage msg = mailer.NewOrder(emailTo);
msg.Send();
And the message goes, it takes a while. And since this kind of operation might be called quite a few times, it will overall slow down the whole process, which I do not wish.
So my question is: how should I handle mail processing? Is there an asynchroneous thing I may use that will do the job? Do I store them in a database table and send them sometimes? I've heard about Task in windows .Net, but I've never used any, is that an option?
I'm looking for suggestions, so feel free to share your opinion! Thank you!
You can use SmtpClient.SendMailAsync using the async-await keywords
public async Task SendSmtpMailAsync()
{
SmtpClient smtpClient = new SmtpClient();
MailMessage mailMessage = new MailMessage("FromAddress", "ToAddress", "Subject", "Body");
await smtpClient.SendMailAsync(mailMessage);
// Possibly do more stuff here.
}
When you await on an asynchronous method, control yields back to the caller. What that means is that the ASP.NET can process messages in the meantime using the thread that returned to the ASP
NET ThreadPool from that same method. When the method finishes, it will return back to the awaited line and continue execution.
Note that using this async alone wont return the request to the caller, it will simply let you process more requests in the meanwhile. What you can do is use this method in correlation with a producer-consumer style collection, like BlockingCollection<T>, add your messages to it and return the response to you caller. In the background, use SendMailAsync to execute these requests.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get a specific socket and close it
I want to know a way to close an existing socket connection from a different process (In Windows). I don't have handle to the socket, I only know the port number. I think I may need to write kernel level code to do this. Any references in C#, or C++?
There are many ways to do that.
One of them is to inject a dll into the target process which will wait, for a packet or an other signal, to be sent by your main process and then close the socket.
Or you could just send a packet to the already open socket that will trigger an exception and therefore the deletion of the socket but I doubt that's going to be any easier than injecting a DLL.
Or maybe you could send a FIN signal to the open socket.