I have a simple wpf application that continues to run even after I explicitly call it to shut down.
It integrates with a third party application and needs to check that a few documents of a certain type and with specific content are open as it initializes.
Here is a portion of the initialization code:
try
{
ActiveProductDoc = Automation.CATIA.ActiveDocument as ProductDocument;
}
catch
{
InvalidAssemblyShutdown("You must have an assembly open before you run the app");
}
if(ActiveProduct == null)
InvalidAssemblyShutdown("You must have one assembly open (not a part)");
ActiveProduct = ActiveProductDoc.Product;
And here is the InvalidAssemblyShutdown method:
private void InvalidAssemblyShutdown(string message)
{
MessageBox.Show(message);
Close();
Application.Current.Shutdown();
}
I have set the application's ShutdownMode property to OnMainWindowClose.
I am currently doing a use case test where the user has the wrong type of document open and so the ActiveProduct field is null. The InvalidAssemblyShutdown method is called as expected but despite this the line in the initialization method following the shutdown call still runs and throws an exception.
Any ideas what's going on?
Should I throw exceptions instead and use a global exception handler?
If you have a look at the source code for Application.Current.Shutdown (link to source), you'll see that it uses Dispatcher.BeginInvoke() to initiate the shutdown. In other words, the shutdown gets queued on the UI thread. It doesn't take effect during that precise method call, so the following code keeps executing.
You'll need to exit the code right after the call to Application.Current.Shutdown if you don't want some code to run while the shutdown request gets processed. Something like:
if(ActiveProduct == null)
{
InvalidAssemblyShutdown("You must have one assembly open (not a part)");
return; // prevent further code execution.
}
For what it's worth, this.Close() works in a similar way. So if you have proper flow control, you won't need to invoke Application.Current.Shutdown at all. Your call to this.Close() should be enough.
Related
I am trying to shutdown a StreamExecutionEnvironment that is started during one of our junit Integration tests. Once all the items in the stream are processed i want to be able to shutdown this execution environment in a deterministic fashion.
Right now when i call StreamExecutionEnvironment.execute method it never returns from that call.
[May be I am too late here, but will answer for those people who are looking for an answer or hint]
Actually what you need to do is gracefully exit from the SourceFunction<T>.
Then the whole StreamExecutionEnvironment will be auto closed. To do that, you may need a special end event to send into your source function.
Write or extend (if you are using pre-defined source function) to check the special incoming event, which will be emitted at the end of your integration tests, and break the loop or unsubscribe from the source. The basic pattern would be shown below.
public class TestSource implements SourceFunction<Event> {
public void run(SourceContext<T> ctx) throws Exception {
while (hasContent()) {
Event event = readNextEvent();
if (isAnEndEvent(event)) {
break;
}
ctx.collect(event);
}
}
}
Depends on your situation, in junit tests, you should send this special event at the end of each/all test cases.
// or #AfterClass
#After
public void doFinish() {
// send the special event from a different thread.
}
Sometimes you might have to do this from a different thread (basically where you generate test events). Not like above.
It is recommended you having a separate source function implementation for your tests because of this matter, so it is easier to modify to accept a special close event. But never in your actual source function which is expecting to go into the production. :)
The javadoc of SourceFunction also explains about a stop() function, which you can see an example from how TwitterSource has been implemented.
Gracefully Stopping Functions
Functions may additionally implement the {#link
org.apache.flink.api.common.functions.StoppableFunction} interface.
"Stopping" a function, in contrast to "canceling" means a graceful
exit that leaves the state and the emitted elements in a consistent
state
.
The SERVICE_STATUS documentation says this structure has to filled out when calling the SetServiceStatus() function.
The third field is dwControlsAccepted.
Unfortunately I have not found any information about which control codes MUST ALWAYS be implemented/react to, at least.
The page says:
By default, all services accept the SERVICE_CONTROL_INTERROGATE value.
But, is there a problem when the service control handler does not react to the SERVICE_CONTROL_STOP control code? Is there a problem when the service control handler does not at least call SetServiceStatus() in this case?
As far as dwControlsAccepted is concerned, there are no mandatory control codes. You can set this value to zero if that meets your needs. Apart from SERVICE_CONTROL_INTERROGATE your code does not need to handle any control codes that you have not specified as acceptable.
For example, if you have not set SERVICE_ACCEPT_STOP then Windows will never send you the SERVICE_CONTROL_STOP control. Any attempt to stop the service will result in error 1052, "The requested control is not valid for this service."
Note that unless you have a specific need to perform a clean shutdown (for example, because you have a database file that has to be properly closed) you do not need to accept shutdown controls either. Such a service will continue to run until the computer is actually powered down.
If you always set dwControlsAccepted to zero, this is all you need for a control handler:
static DWORD WINAPI ServiceHandlerEx(DWORD control, DWORD eventtype, LPVOID lpEventData, LPVOID lpContext)
{
if (control == SERVICE_CONTROL_INTERROGATE)
{
return NO_ERROR;
}
else
{
return ERROR_CALL_NOT_IMPLEMENTED;
}
}
I have a SQL Sever 2008 R2/64-bit database server for which I'm writing some fairly basic scripting utilities with the Sql Server Management Objects (SMO). My project is a 32-bit VS2010 executable written in C#.
Most of the effort has been fairly simple and successful. The only problem I'm having is in the firing of my custom event handler that should be called in response to a Scripting Error.
The Scripter object exposes a ScriptingError event, which I have attempted to leverage thusly:
//srv contains a valid server name
Scripter scrp = new Scripter(srv);
//scrp_ScriptingError is my handler
scrp.ScriptingError += new ScriptingErrorEventHandler(scrp_ScriptingError);
My handler is declared thusly:
static void scrp_ScriptingError(object sender, ScriptingErrorEventArgs e)
{
// my handler goes here, just printing e.Current.Urn to the console
// This is merely representative, have had other things here, but
// the handler never fires
Console.WriteLine(e.Current.Value);
}
All this compiles cleanly.
My code is invoked via simple scrp.Script(urns); where urns is just an array of the database objects being scripted out. Nothing fancy:
try
{
sc = scripter.Script(urns);
}
catch (Exception e)
{
WriteLog(String.Format("Failure during scripting: {0}: Inner exception message (if any): {1}",e.Message,((e.InnerException==null)?"[None]":e.InnerException.Message)));
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName,true))
{
foreach(String currentLine in sc)
{
file.WriteLine(currentLine);
file.WriteLine("GO");
}
}
The problem is that, no matter what I've tried so far, when errors occur during scripting, my ScriptingError handler never fires.
Even in debug mode within VS2010, when I set a breakpoint within the handler, and fire my scripting code, and know an error will occur, only an exception will be thrown, but the breakpoint in my ScriptingError handler never trips.
I'm in trees-for-forest mode now, not sure what I've done wrong. Am I expecting the wrong things for the ScriptingError handler?
I have searched the MSDN docs on the SMO objects and found virtually nothing on ScriptingError handlers other than the basic API calls themselves, and precious few examples on the Internet. It seems incredibly simple and straightforward to me - just assigning an event handler to the event - but there's some battery-not-included notice I've failed to note.
Pointers to my error are greatly appreciated, with a polite request for minimal brickbats if the error is exceptionally stupid on my part :)
I am not at a pc right know, but I think you should try to set the ContinueScriptingOnError option. Otherwise there would be no reason for SMO to invoke the event, but rather through an exception instead.
I thought I knew what causes this exception until I wrote this:
var menu = ViewConfigHelper.CreateObjectFromResource<Menu>(config, baseURI);
if (!menu.Dispatcher.CheckAccess())
{
throw new ArgumentException("Somethign wrong");
}
if (!LayoutRoot.Dispatcher.CheckAccess())
{
throw new ArgumentException("SOmethign wrong");
}
// exception throw here
LayoutRoot.Children.Insert(0, menu);
First line creates a Menu control from an embedded XAML file. Both CheckAccess calls return true. However, when last line is executed, an exception is thrown with the message "Caling thread cannot access object because differrent thread owns it." The code above is being executed within a method called immediately after InitializeComponent() that created LayoutRoot, on the same thread, I believe.
Someone please enlighten me. I am trying to create a multiple UI thread WPF app.
You are using CheckAccess() in reverse. You want to lose the ! signs before each check. See the example bit of code on the CheckAccess() MSDN page.
In the Winforms world you'd do a InvokeRequired() which is now the same thing as a !CheckAccess(). In your case because both values are returning true, and you are inverting them, neither if block is hit.
To expand a bit... in the Winforms world, the normal patter was:
if(InvokeRequired)
{
Invoke(...);
}
else
{
//do work
}
(or sometimes a return after invoke, if it was invoking the same method).
In WPF, CheckAccess() is similar to, but not identical to InvokeRequired... there for a pattern more along the lines of:
if (someUiControl.Dispatcher.CheckAccess())
{
//Doing an update from this thread is safe, so we can do so here.
}
else
{
// This thread does not have access to the UI thread.
// Call the update thread via a Dispatcher.BeginInvoke() call.
}
The key difference between is that InvokeRequired() returning true meant it was UNSAFE to do the update in the current thread... while a true from CheckAccess() means it is SAFE.
I am trying to reuse some .NET code that performs some calls to a data-access-layer type service. I have managed to package up both the input to the method and the output from the method, but unfortunately the service is called from inside code that I really don't want to rewrite in order to be asynchronous.
Unfortunately, the webservice code generated in Silverlight only produces asynchronous methods, so I was wondering if anyone had working code that managed to work around this?
Note: I don't need to execute the main code path here on the UI thread, but the code in question will expect that calls it makes to the data access layers are synchronous in nature, but the entire job can be mainly executing on a background thread.
I tried the recipe found here: The Easy Way To Synchronously Call WCF Services In Silverlight, but unfortunately it times out and never completes the call.
Or rather, what seems to happen is that the completed event handler is called, but only after the method returns. I am suspecting that the event handler is called from a dispatcher or similar, and since I'm blocking the main thread here, it never completes until the code is actually back into the GUI loop.
Or something like that.
Here's my own version that I wrote before I found the above recipe, but it suffers from the same problem:
public static object ExecuteRequestOnServer(Type dalInterfaceType, string methodName, object[] arguments)
{
string securityToken = "DUMMYTOKEN";
string input = "DUMMYINPUT";
object result = null;
Exception resultException = null;
object evtLock = new object();
var evt = new System.Threading.ManualResetEvent(false);
try
{
var client = new MinGatServices.DataAccessLayerServiceSoapClient();
client.ExecuteRequestCompleted += (s, e) =>
{
resultException = e.Error;
result = e.Result;
lock (evtLock)
{
if (evt != null)
evt.Set();
}
};
client.ExecuteRequestAsync(securityToken, input);
try
{
var didComplete = evt.WaitOne(10000);
if (!didComplete)
throw new TimeoutException("A data access layer web service request timed out (" + dalInterfaceType.Name + "." + methodName + ")");
}
finally
{
client.CloseAsync();
}
}
finally
{
lock (evtLock)
{
evt.Close();
evt = null;
}
}
if (resultException != null)
throw resultException;
else
return result;
}
Basically, both recipes does this:
Set up a ManualResetEvent
Hook into the Completed event
The event handler grabs the result from the service call, and signals the event
The main thread now starts the web service call asynchronously
It then waits for the event to become signalled
However, the event handler is not called until the method above has returned, hence my code that checks for evt != null and such, to avoid TargetInvocationException from killing my program after the method has timed out.
Does anyone know:
... if it is possible at all in Silverlight 3
... what I have done wrong above?
I suspect that the MinGatServices thingy is trying to be helpful by ensuring the ExecuteRequestCompleted is dispatched on the main UI thread.
I also suspect that your code is already executing on the main UI thread which you have blocked. Never block the UI thread in Silverlight, if you need to block the UI use something like the BusyIndicator control.
The knee-jerk answer is "code asynchronously" but that doesn't satisfy your question's requirement.
One possible solution that may be less troublesome is to start the whole chunk of code from whatever user action invokes it on a different thread, using say the BackgroundWorker.
Of course the MinGatServices might be ensuring the callback occurs on the same thread that executed ExecuteRequestAsync in which case you'll need to get that to run on a different thread (jumping back to the UI thread would be acceptable):-
Deployment.Current.Dispatcher.BeginInvoke(() => client.ExecuteRequestAsync(securityToken, input));