The following error is occuring when passing values from a model to a parameter inside an If Statement.
This is the code the issue is occurring, I'm pretty sure its not the ValidateUserPassword method.
if (PSFNetSystem.ValidateUserPassword(model.Server, model.Username, model.Password) < 0)
{
ModelState.AddModelError("Password", "Failed to login");
return View(model);
}
Any help is appreciated, thanks.
Short answer: You can click on the "thread" icon to the right to force the evaluation.
Long answer:
When you evaluate a method in the debugger, the debugger/CLR sets the context of the current thread to the method being evaluated, sets a guard breakpoint, freezes all threads except the current thread, then continues the process. When the breakpoint is hit, the debugger restores the thread to its previous state and uses the return value to populate the window.
Because only one thread is running, it's possible to create deadlock situations if the evaluation thread takes a lock that's already held by another thread. If the CLR detects a possible deadlock it aborts the evaluation and the debugger ultimately shows that message.
Clicking the button to allow all threads to run means that we don't freeze the other threads when retrying the evaluation. This will allow the evaluation to proceed, but has the disadvantage of breakpoints on other threads being ignored.
BTW, If you are writing code that you know will likely deadlock if it's evaluated, you can call Debugger.NotifyOfCrossThreadDependeny. This will cause the behavior you are seeing.
It is because it needs to run the code to show you the result in the debugger. You can press the icon at the right to evaulate it, or you can go to Options -> Debugging and turn off "Enable property evaluation or other implicit function calls".
Related
I'm pretty new to FRP and I'm facing a problem:
I subscribe to an observable that triggers subscribeNext every second.
In the subscribeNext's block, I zip observables that execute asynchronous operations and in zip's completed block I perform an action with the result.
let signal: RACSignal
let asynchOperations: [RACSignal]
var val: AnyObject?
// subscribeNext is trigered every second
signal.subscribeNext {
let asynchOperations = // several RACSignal
// Perform asynchronous operations
RACSignal.zip(asynchOperations).subscribeNext({
val = $0
}, completed: {
// perform actions with `val`
})
}
I would like to stop the triggering of subscribeNext for signal (that is normally triggered every second) until completed (from the zip) has been reached.
Any suggestion?
It sounds like you want an RACCommand.
A command is an object that can perform asynchronous operations, but only have one instance of its operation running at a time. As soon as you tell a command to start execute:ing, it will become "disabled," and will automatically become enabled again when the operation completes.
(You can also make a command that's enabled based on other criteria than just "am I executing right now," but it doesn't sound like you need that here.)
Once you have that, you could derive a signal that "gates" the interval signal (for example, if:then:else: on the command's enabled signal toggling between RACSignal.empty and your actual signal -- I do this enough that I have a helper for it), or you can just check the canExecute property before invoking execute: in your subscription block.
Note: you're doing a slightly weird thing with your inner subscription there -- capturing the value and then dealing with the value on the completed block.
If you're doing that because it's more explicit, and you know that the signal will only send one value but you feel the need to encode that directly, then that's fine. I don't think it's standard, though -- if you have a signal that will only send one value, that's something that unfortunately can't be represented at the type level, but is nonetheless an assumption that you can make in your code (or at least, I find myself comfortable with that assumption. To each their own).
But if you're doing it for timing reasons, or because you actually only want the last value sent from the signal, you can use takeLast:1 instead to get a signal that will always send exactly one value right at the moment that the inner signal completes, and then only subscribe in the next block.
Slight word of warning: RACCommands are meant to be used from the main thread to back UI updates; if you want to use a command on a background thread you'll need to be explicit about the scheduler to deliver your signals on (check the docs for more details).
Another completely different approach to getting similar behavior is temporal recursion: perform your operation, then when it's complete, schedule the operation to occur again one second later, instead of having an ongoing timer.
This is slightly different as you'll always wait one second between operations, whereas in the current one you could be waiting anywhere between zero and one seconds, but if that's a not a problem then this is a much simpler solution than using an RACCommand.
ReactiveCocoa's delay: method makes this sort of ad-hoc scheduling very convenient -- no manual NSTimer wrangling here.
So i've got this code that tries to find an unused upload name, using the user's email and a number at its end. It does this with a list of uploaded objects we've already collected, the user's email.(upload_name), and the
current number that might be open (it is incremented when a match is found).
The list is not sorted, and it's pretty tricky to sort for a few reasons, so I'm having the method read through the list again if it reaches the end and the upload_number has changed.
- (NSString*)findUnusedUploadNameWithPreviousUploads:(NSMutableArray*)objects withBaseUploadName:(NSString*)upload_name {
previous_upload_number = upload_number;
for (NSString *key in objects) {
// the component of the object name before the first / is the upload name.
NSLog([key componentsSeparatedByString:#"/"][1]);
if ([[key componentsSeparatedByString:#"/"][1]
isEqualToString:([NSString stringWithFormat:#"%#_%ld", S3KeyUploadName1, upload_number])]) {
upload_number++;
NSLog([NSString stringWithFormat:#"upload name: %#_%ld", S3KeyUploadName1, upload_number]);
}
NSLog(#"pang");
}
NSLog(#"ping");
if (previous_upload_number == upload_number) {
return [NSString stringWithFormat:#"%#%ld", upload_name, upload_number];
}
return [self findUnusedUploadNameWithPreviousUploads:objects withBaseUploadName:upload_name];
}
The problem is, the program never reads the "ping". it just leaves the method after the first for loop is done.
Edit: No the NSlogs are fine, you can do simple string OR StringWithFormat.
Edit: Don't mind the unnecessary use of recursion, I did this because the simple way was having the same problem and i wanted to see if a different (albeit unnecessarily recursive) way would share that problem. It does.
Edit: I set a breakpoint in the for loop, and I set a break point at the "ping". It does not reach the ping. It completes the for loop and the ditches the whole thing.
Edit: Please try to help me figure out why it's exiting the the method immediately after the for loop. I'm aware this is stylistically meh, and I promise I'll make it shiny and spotless when it works. =]
Edit: to be clear, the method DOES exit. it does so early I know this because the rest of the program following this method (which is not threaded such that it wouldn't have to wait for it) runs AFTER this for loop, consistently.
There are a couple of possible explanations for the described behavior:
The method never exits. For some reason it blocks or performs infinitely somewhere in the loop. Make sure this is not the case by setting a breakpoint after the place where the message is called (i.e. the place to where it should return).
The method, or some method it calls, throws an exception. While seldom and unsupported in productive Cocoa code it could be some misbehaving 3rd party library or just a simple programmer error, where Cocoa actually does throw. Make sure this does not happen by setting an exception breakpoint in Xcode.
Undefined behavior. This is, sadly, part of official C and heavily exploited by modern compilers. It basically means: Anything can happen, if there's something in your code, where the standard says that the behavior is not defined. One example would be accessing a deallocated object. Another fine reason of undefined behavior can be threads accessing common data in an unsynchronized way.
Other than exceptions there's no explanation for a method to "exit early". If you still can't find the reason I suggest you invest some time to learn the debugger. Single stepping, like Aris suggested, might be a way to find out what's going on.
I have seen in many places (including Apple Dev Forum) that to test async operations some developers recommend grabbing current run loop and let it run for a while to force async blocks to get called. e.g.
__block id returnedModel = nil;
BOOL result = [binder fetchAndBind:...
successBlock:^(id *model) { returnModel = model; }
errorBlock:nil];
NSDate *loopUntil = [NSDate dateWithTimeIntervalSinceNow:10.0f];
BOOL isModelReturned = (returnedModel != nil);
while (!isModelReturned && [loopUntil timeIntervalSinceNow] > 0)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:loopUntil];
isModelReturned = (returnedModel != nil);
}
There are differnet flavors to the above implementation but the concept is the same. Some are using dispatch_group, etc.
Questions:
Does Apple have any documentation about testing async operations (I couldn't find any)?
From unofficial sources I have read that unit tests are
self-contained in the run loop they are running. So they are not
supposed to be treated as above. Is that true? Is this documented by
Apple somewhere?
With Xcode 5.1 the above implenetation or dispatch_group result in EXC_BAD_ACCESS (code=2, address=0xd). Is it because of the concept that unit test are self-contained in their own thread and should not be treated like this?
I have seen problems and side effects with such approaches, particualrly if one or more objects in that test are mocked. Side effects like causing the app to crash so that unit tests can't be completed. For example a method in Class A that its public API takes an NSArray as input crashed because a test mocked an object, let run loop continue, that object then started interacting with Class A and since it was mocked, it passed in a dictionary! -- whereas if run loop was not forced to continue, the object would have been un-mocked later and every test would be happy!
I personally think there is no reason to test async. There is an operation that's running in an async fashion. It is that operation/function that needs to be tested not async.
I am looking for some references or documentation (perferrably from Apple) to clearly talk about async unit tests, whether the run loop of a unit test can be forced to continue, or what is the recommended approach for testing async operations with XCTests.
Thanks!
Edit:
In Xcode 6 the XCTest framework ships with async testing macros. I leave this question here for reference.
There are a few misconceptions regarding your example code:
First off, if the completion handler will be executed on a different thread than where the call-site executes, the compiler will create code that is "undefined behavior". This is due to modifying the variable returnedModel in thread "A" and reading the value in thread "M". This is a classic "data race" which produces undefined behavior (please read more in the C and C++ specification).
The __block modifier may alleviate this issue, but I don't believe clang takes special actions here. In the worst case, the thread reading the value (the main thread) never "sees" an update of the value performed through the handler or it reads "garbage".
Another problem with this approach requires a more thorough understanding how Run Loops do actually work. In your example, in the worst case, the run loop's method runMode:beforeDate: will only return when the timeout expired - that is after 10 secs. It may return earlier only if there was an event processed on this mode - possibly unrelated to the test code.
So in short, this approach isn't really suited to accomplish the task. But other "flavors" may indeed work.
According your questions:
Q1: No.
The reason is probably, that XCTest is actually quite old (its just another name for SenTest), and code at the time where it was invented had probably no such fancy stuff like "asynchronous operations", "blocks" and "completion handlers". So there's no built-in solution for this task.
Q2: I don't quite understand this questions. But we might assume that "matchers" (aka "assert something") use exceptions when the test fails. Those require to be executed on the main thread, where there is a catch handler implemented by the underlying test implementation. Maybe XCTest doesn't use exceptions - however, other Unit Test libraries may indeed use exceptions - for example "Cedar". That means, if you execute a completion handler on some queue, and a matcher throws an exception, it MUST be executed on the main thread. (bummer).
Q3: Perhaps the exception issue? But I have no idea. Possibly there's another issue. You may provide more information.
The other "side" effects may be "race conditions" or other issues. But unless you provide more detailed info I'm guessing ;)
Whether or not there is a need to "test async" really depends on what you are actually testing:
For example, if you use a well known third party network library which has a completion handler, would you really want to test whether the handler will be invoked? (Probably not, since you wouldn't want to actually test the network library).
But if you implemented your own asynchronous operation which reports the result via a completion handler, you actually may want to test whether a completion handler will be invoked.
As far as I understand, pthread_exit() exactly equals to return when you need terminate a thread with a return value. When people can use the consistent way, i.e. return, to do the job why Pthread define such a duplicated interface?
Two reasons that come to my mind: pthread_exit
Allows you to exit a thread from any depth in the call stack.
Must be called on the main thread if the TLS keys for the main thread are to have their free functions called. And here as well: "Any cancellation cleanup handlers that have been pushed and not yet popped are popped in the reverse order that they were pushed and then executed. After all cancellation cleanup handlers have been executed, if the thread has any thread-specific data, appropriate destructor functions will be called in an unspecified order... An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it. The function's return value serves as the thread's exit status."
If you're going to call pthread_exit a duplicated interface, then you should also call exit() a duplicated interface, since you could exit the program at an arbitrary point. You probably want to call pthread_exit() when you have some sort of error condition where you simply cannot continue. Or, alternatively, you've found whatever value you're looking for inside of the thread.
As for it's real existence, according to the documentation:
An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it. The function's return value serves as the thread's exit status.
So if you did a return <some pointer> from the thread, or simply reached the end, pthread_exit() would be called anyway. It's the same with exiting from main(), if you return 0 you're actually calling exit(0). The function has to exist, otherwise the kernel would not have a way of determining if the thread exited.
In delphi, a method in TThread is terminate. It seems a subthread can not kill another thread by calling terminate or free.
For example
A(main form), B (a thread unit), C (another form).
B is sending data to main form and C (by calling syncronize), we tried to terminate B within C while B is executing by calling B.terminate. But this method does not work and B is still working until it ends in execute method.
Please help. Thank you in advance.
You have to check for Terminate in the thread for this to work. For instance:
procedure TMyThread.Execute;
begin
while not Terminated do begin
//Here you do a chunk of your work.
//It's important to have chunks small enough so that "while not Terminated"
//gets checked often enough.
end;
//Here you finalize everything before thread terminates
end;
With this, you can call
MyThread.Terminate;
And it'll terminate as soon as it finishes processing another chunk of work. This is called "graceful thread termination" because the thread itself is given a chance to finish any work and prepare for termination.
There is another method, called 'forced termination'. You can call:
TerminateThread(MyThread.Handle);
When you do this, Windows forcefully stops any activity in the thread. This does not require checking for "Terminated" in the thread, but potentially can be extremely dangerous, because you're killing thread in the middle of operation. Your application might crash after that.
That's why you never use TerminateThread until you're absolutely sure you have all the possible consequences figured out. Currently you don't, so use the first method.
Actually,
currently most voted answer to this question is incorrect (so as 34 upvoters...) in regard how to forcefully kill a thread.
You do not use ThreadId as a parameter to TerminateThread procedure. Using ThreadId will cause most likely an "Invalid handle" error or in worse case scenerio - will kill a different thread.
You should pass a thread handle as a parameter:
TerminateThread(MyThread.Handle);
More about differences between thread's handle and id can be found here.
Edit
Seems #himself corrected his mistake after seeing my answer, so this is no longer relevant.
Terminate does not kill a thread; it sets the Terminated property to inform the thread that it needs to terminate. It's the thread's responsibility to watch for Terminated and shut itself down gracefully.
All the Terminate method does is it sets the Terminated property to true. So you have to manually keep checking that property and then exit the thread method when it is set to true.
If you might want to terminate a thread then you could be better off spawning another app and killing that if you think its failed - windows will then tidy up after you.