I've made a project than uses tcp sockets connectivity (own closed protocol), added background connectivity with Network Trigger API, as described here (starting from page 17) - StreamSocket control channel registration block, and IBackgroundTask class, that should be fired each time socket receives something.
Have tried everything to debug the code in background task, with no use:
closing the visible app with a gesture
lock the screen
tried to load some other heavy application, to make windows suspend my app
All these have not helped me to make background task run (and debug) during socket message. What am I doing wrong? Should I have to get the separate suspendable device, like a WinRT tablet, to get this working?
By default referenced projects are not added to the main one. This is not so obvious as it may seem, and that's why I spent almost a week to find out this. So the clue is: check reference projects accessibility.
Upd:
There are some more things to deal with, as I've found out during development. Some of them are not as clear as they need to. Here is a list of what I did:
Add background project to main project's references (right click on references node in solution browser).
Check if main project manifest contains right declaration (background task w/control channel, right background entry point name with full package, $targetnametoken$.exe as executable)
A thing that leads from #1: all the entities you plan to use within background, should be put into separate project in solution. This project is then referenced by both main and background projects.
Be aware of BackgroundExecutionManager.RequestAccessAsync() to be called before registering ControlChannelTrigger
A key thing I've found just in one small comment in a sample project:
// IMPORTANT: When using winRT based transports such as StreamWebSocket with the ControlChannelTrigger,
// we have to use the raw async pattern for handling reads instead of the await model.
// Using the raw async pattern allows Windows to synchronize the PushNotification task's
// IBackgroundTask::Run method with the return of the receive completion callback.
// The Run method is invoked after the completion callback returns. This ensures that the app has
// received the data/errors before the Run method is invoked.
// It is important to note that the app has to post another read before it returns control from the completion callback.
// It is also important to note that the DataReader is not directly used with the
// StreamWebSocket transport since that breaks the synchronization described above.
// It is not supported to use DataReader's LoadAsync method directly on top of the transport. Instead,
// the IBuffer returned by the transport's ReadAsync method can be later passed to DataReader::FromBuffer()
// for further processing.
More info here - http://code.msdn.microsoft.com/windowsapps/ControlChannelTrigger-91f6bed8/sourcecode?fileId=57961&pathId=2085431229
If you did all things properly, the debugging of background tasks is straightforward. Just put the breakpoint and go on, nevermind of main project is running or suspended.
ps - If the project is suspended, be aware of calling UI thread (especially awaited things) - they won't run until app is running, and will wait.
Related
I try to develop an extension for Microsoft Edge based on native messaging and the official guide provides the example. And there is synchronization of access to the dictionaries of AppServiceConnections and their Deferrals in the OnBackgroundActivated method, but there is no such a thing in other event handling methods...
So my question is about UWP App Service threading model. Is it guaranteed that only one event handling method can be performed at a time? Or should I provide a correct synchronization of access to my data?
Is AppServiceConnection thread safe? Can I use SendMessageAsync from different threads at the same time? Or should I synchronize its usage?
I guess your issue is that you didn't see lock keyword inside events like OnAppServiceRequestReceived, OnAppServicesCanceled and so on, which is to do thread synchronization, and you're not sure if you should do this by yourself.
I think the answer should be no.lock inside OnBackgroundActivated is ensured to set correct desktopBridgeConnectionIndex or connectionIndex. Without the keyword lock inside these event handles not means that the event handle must be triggered only one time at a time. For one app service, if client A is connecting the app service, at the same time, another client B asks for the same app service, for this scenario the app service will spin up another instance of the same background task. So that for client A, its app service connection there is no side effect on client App B. In another words, each app service connection has its own instance, messages sending based on one app service connection have no influence with others. You may reference this video to look more details about app service, app service relative is about starting from 25th minute.
If you check the code snippet inside the event, you may see there are code lines to judge the request is from which app service connection, for example this.desktopBridgeConnection = desktopBridgeConnections[this.currentConnectionIndex].You will send message to correct AppServiceConnection, and this should be thread safe. If you met actual thread save issue when performing this, you could ask issue with testing details.
I have a C# winforms project which has a reference to a library also coming from myself. The winforms app triggers some work to do for the library. Is it possible that the library can finish its work even if the winforms app gets closed?
There are two possible approaches:
create a separate subprocess. Ending the parent process will not end the child, thus, the newly created task will continue when the parent app is closed
make the parent app in such way that closing the main form doesn't end the application, thus, giving the application time to end all worker threads spawned during its lifetime
I am not sure which of the two I would recommend, both seem risky as chances are the long-running background operation will not finish in reasonable time. And then what?
Is it possible that the library can finish its work even if the
winforms app gets closed?
No, not if that library is simply hosted in the main process.
You would need to do something along the lines of create a windows (or web) service and host the library in the service along with a message passing mechanism. Then call into it by having your windows application call a command on the service.
I have a very long running workflow that moves video files around between video processing devices and then reports the files state to a database which is used to drive a UI
At times the users press a button on the UI to "Accept" a file into a video storage server. This involves copying a file from one server to another.]
They have asked if this activity can be cancelled.
I've looked at the wf4 documentation and I can't see a way to roll back part of a workflow.
Is this possible and what technique should I use.
The are two basic inbuild activities for reverting work.
The TransactionScope for ACID transaction
The Compensable activity for long running work.
With the Compensable activity you add activities to the compensation handler to undo work previously done. The Compensate activity can be used to trigger compensation. If there is no compensation you will get the confirmation handler either at the end of the workflow automatically or when you use the Conform activity.
See A Developer's Introduction to Windows Workflow Foundation (WF) in .NET 4 by Matt Milner for more details.
Okay, so let's first say that the processing of "rolling back" what was already uploaded will have to be done by hand, so where ever you're storing those chunks you'll need to clean up by hand when they cancel.
Now, on to the workflow itself, in my opinion you could setup your FlowChart like this:
Alright so let's break down this workflow. The entire service should be correlated on some client key so that way you can start the service with Start once per client to keep the startup costs down.
Next, when said client wants to start a transfer you'll call BeginTransfer which will move into the transfer loop. The transfer loop is setup so that you can cancel between chunks if necessary by calling CancelTransfer.
That same branch, in this model, is used to finish the transfer as well because it gets out of the loop, so when your done transferring chunks just call CancelTransfer (if you don't like that just setup a different branch that looks exactly the same).
Finally, when you're in the process loop, you can SoftExit the entire workflow and shut it down so that you can kill it softly if there is necessary maintenance or when the client is finished with its connection it needs to call SoftExit to dispose of it.
not sure if I totally understand your scenario but I think you would need to run your transfer process on an asynchronous thread, that from time to time check a "cancel" variable to perform a rollback. This variable can be modified on the main thread on your UI.
Of course, this will allow you to cancel between transfers, not in the midle on one single transfer.
I’m building a small WP7 app that need to access/update several resource over the web. I’m looking to build a PriorityThreadPool object with some cancellation feature to help me running “Action” on several Thread on the background. Well the custom thing download in priority what the user is seeing then download the rest but if the user update the visual then change the priority and make those item appear upper in the propriety list of the pool.
Let’s say I’m implementing an action responsible to download an Image from a web server would you try to make the Async call sync or will you just leave it as is, please take in consideration that I may run 100 action that download 100 different image. Perhaps If I do not make the call sync It will be pretty difficult to cancel an action since they will all run pretty fast in the thread pool. I guess that under the hood there some sort of thread pool for the network connectivity on WP7
Any comments or suggestion.
Rather than try and (re?)create a "PriorityThreadPool" I'd create an object which manages multiple queues which you can adjust the priority of as necessary.
This could then process each queue depending upon priority.
When processing the queue, only issue a few requests at once and start the next when one finishes.
You could do the processing on the ThreadPool or by creating a BackgroundWorker if you want greater control over being able to cancel requests.
Within each request you may want to process it as a synchronous operation as it will make the logic simpler but will make cancelling things harder.
I have a c# .NET multi-threaded application that is freezing the interface. What is unusual about this is that the interface does not freeze unless I let the system sit idle long enough for the screen saver to start (which requires me to reenter my password to re-gain access to the system). When the interface becomes visible again (after I have successfully entered my password) the interface is locked up. As long as I don't let the screensaver start, then the interface does not lockup.
I should point out that I have two different executables that access the same dll and this problem is occurring no matter which application I use to access the DLL. This seems to imply that the problem is in the DLL as the two applications are completely different (C++/MFC) and (C#/.NET) apart from how they relate to the DLL.
Both exes perform similar steps in how they interact with the DLL. They make calls into the dll to setup the serial port communication, open a status window in the DLL, start a thread in the DLL to monitor the comm port, and then starts a thread in the main app that monitors a stack in the dll.
When data is obtained from the comm port by the thread in the DLL, it is parsed and its results are placed on the stack and then posted to the status window via a delegate. When the thread in the exe sees data in the stack, it outputs the data in the main window, also using a delegate.
I found that if I add code to the thread inside the DLL so it calls Application.DoEvents() every 30 seconds, the interface will be frozen for about 30 seconds and then resume activity like normal.
I figure something is blocking the main thread and forcing DoEvents() to fire seems to break the lock, but I have no idea what might be causing this lock.
This issue occurs both on my development machine and on a test machine.
I have tried completely removing the output of data to the status window inside the DLL, but that didn't make any difference.
I have been doing multi-threaded programming for years and never seen anything like this; so any advice would be greatly appreciated.
Thanks.
This is a problem that's commonly induced by the SystemEvents class when you have a non-standard way to initialize your user interface. Using threads, specifically. Start your program, Debug + Break All, Debug + Windows + Threads. If you see a thread named ".NET SystemEvents" then you're pretty much guaranteed to get this hang.
Some background: the SystemEvent class supports both console mode apps and GUI apps. For the latter, it should fire its event handlers on the UI thread. The very first time one of its events is subscribed, it creates a little invisible helper window to get the system notifications. It can do this two ways, either by creating the window on the calling thread or by starting up a helper thread. It makes the decision based on the value of Thread.GetApartmentState(). If it is STA then it can create the window on the calling thread and all event callbacks can be properly marshaled to that thread.
This goes wrong if the first window you create is not created on the UI thread. A splash screen for example. That window may contain controls that are interested in a system event like UserPreferenceChanged so they can properly repaint themselves. It now uses the helper thread and any event will be fired from that helper thread, not the UI thread. Poison to any window that runs on the UI thread. The session switch out of a locked workstation (including the screen saver) is for some mysterious reason very likely to cause deadlock. You may also see an occasional painting mishap, the less nasty result of using windows from the wrong thread.
Short from fixing the initialization order, a workaround is to put this in your Main() method, before any windows are created:
Microsoft.Win32.SystemEvents.UserPreferenceChanged += delegate { };
The problem does appear to be related to the ActiveX control is was probably using incorrectly in a form. I switched to using the serial port library in .NET and have not been able to reproduce my problem. Thanks to everyone, especially Hans for their assistance.
I am having the same issue as my PC just hangs up when the screen saver kicks off or I lock my PC and monitor goes to sleep.
I am 95% sure that there are deadlocks appearing in my multithreaded app. Look and identify whether there are any deadlocks in your code.