views:

42

answers:

2

Sorry for the weird caption. Here's what I'm going to do:

I'm in the client code, calling a method on the server. As a result, the server is going to send certain data to the client. I'd like to validate that these data have arrived within a second, which is necessarily the case unless something went seriously wrong. The code looks like this:

Channel.SendMeData (id);

new Thread (() => {
    Thread.Sleep (1100);
    Debug.Assert (ReceivedData[id] != null);
}) {
    IsBackground = true
}.Start ();

As you can see, I'm creating a new thread solely for Debug.Asserting a condition that relies on successful network code. I can't help but think this is terribly wrong for multiple reasons, but I don't really see how this can be avoided. I did write unit tests, of course, but I like to have the assertion in the main code as well.

+1  A: 

If you can block your current thread, you can simply use Thread.Sleep(1100); in your main block of code, without creating a new thread.

If you can not block other code to wait for this assertion, then it will indeed need to be on a separate thread as per your example.

Mike
Yes, I also thought about blocking the main thread, but that would a) quite severely limit the performance and b) be kind of an ugly hack. Looks like I have to keep the extra thread :\
mafutrct
+4  A: 

I wouldn't assert something like this - Asserts should be for things that should always be true, and indicate a logical error if one failed e.g. loop/class invariants. In this case, you can't control whether you receive a response in a timely manner so you should create a timeout and throw an exception if the response did not arrive before it expired.

Lee
Valid statement, I ought not to use an assertion at all for something like this. Creating a separate timeout as proposed seems like a more reasonable idea.
mafutrct