WrongThreadException in WinRT async handler - asynchronous

WinRT project, C++/CX. I'm trying to load a PNG file into a WriteableBitmap. I'm setting the Source property to an IRandomAccessStream. To get a stream from file, one has to use an async operation - there's no sync file open in WinRT.
My async completion handler is executed, it seems, on a random worker thread. And in that handler, the most innocent operations (like constructing a new WriteableBitmap) cause a WrongThreadException. It's not reproducible from run to run.
What's going on? Should I chalk it up to pre-release funkiness?
Visual Studio 2012 RC, Windows 8 build 8400.

When you interact with UI elements, they need to be performed on the UI thread. The easiest way of ensuring that you're on the UI thread is to use the PPL continuations - if you use the create stream async APIs, then the lambda passed to the ".then" method should run in the thread context of the original thread - usually the UI thread.
If you can't get back to the UI thread via PPL, then use CoreDispatcher.RunAsync() and do your work in the lambda passed to RunAsync - that will always run on the UI thread.

Related

The configured execution strategy 'SqlRetryingExecutionStrategy' does not support user-initiated transactions

I have ASP.Net 4.7.2 window service which is processing NServiceBus messages. Currently it is deployed to On-Premise server. It has retry mechanism as well and working fine. Now I am going to containerizing it. While running into docker window container, it is doing SQL operation using Entity framework and giving exception as mentioned below:
The configured execution strategy 'SqlRetryingExecutionStrategy' does not support user-initiated transactions. Use the execution strategy returned by 'DbContext.Database.CreateExecutionStrategy()' to execute all the operations in the transaction as a retriable unit.
While running locally by installing manually or on On-Premise server, it is working fine but in container it is throwing exception.
Can any one help me what can be the root cause?
It sounds like the piece of code does manual transaction management and is not wrapped within an execution strategy execute.
if your code initiates a transaction using BeginTransaction() you are defining your own group of operations that need to be treated as a unit, and everything inside the transaction would need to be played back shall a failure occur.
The solution is to manually invoke the execution strategy with a delegate representing everything that needs to be executed. If a transient failure occurs, the execution strategy will invoke the delegate again.
https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency#execution-strategies-and-transactions
using var db = new SomeContext();
var strategy = db.Database.CreateExecutionStrategy();
strategy.Execute(
() =>
{
using var context = new SomeContext();
using var transaction = context.Database.BeginTransaction();
context.SaveChanges();
transaction.Commit();
});
``

How ConfigureAwait(false) Prevent Ui Deadlocks

I Know that this question has been asked endlessly, but still. I think i am missing somthing.
When we want updating UI( WinForm UI for the sake of argument ) in asynchronously manner. But we cannot using the async /await keyword and we have to use the ConfigureAwait(false). As i understand it "Tells" the task that it can resume itself on any available thread instead of waiting to to the main thread. Its preventing the deadlock by free the UI for not waiting for the long process to be completed and task is not waiting for the main UI thread to be available.
The following code demonstrate the classical deadlock
public void Button_Click()
{
SomeTextBox.Text =LongProcessAsync().Result;
}
So now my question start :). How eventually UI thread update UI after long proccess task has completed.
Is it because task passing the result to another UI process to complete the job ?
How UI queue message related to that parts ?
When saying only one thread updating the ui , does it mean that this thread live for the all life cycle of the application or only one thread is updating ui but a new thread can be created and do the stuff ?
Thanks
I recommend reading Stephen Cleary's blog post on this topic: Don't Block on Async Code which explains how the deadlock happen and how to avoid it.
Pay attention to the difference of "deadlock" and "blocked UI". Deadlock happens when two threads are waiting for each other, Blocked UI happens when UI thread is busy/blocked and cannot process UI messages. Here using ConfigureAwait(false) doesn't prevent "blocked UI", but prevents "deadlock".
When you write an async library methods which runs a task, to prevent a possible deadlock it's recommended to run your task by ConfigureAwait(false). It's to prevent deadlock even in case the users of your library get the result of your async method by calling Result or Wait.
ConfigureAwait(false) basically tells: not to come back to the original context after this line and continue execution on thread pool thread.
To understand it better, look at this example:
// UI code
1: private void button1_Click(object sender, EventArgs e)
2: {
3: var result = GetDataAsync().Result;
4: MessageBox.Show(result);
5: }
// A library code
6: public async Task<string> GetDataAsync()
7: {
8: await Task.Delay(1000);
9: return "Data";
10: }
Considering the following facts:
In Windows Forms, all UI code executes in a single thread; the UI thread.
Result method of the Task blocks the calling thread until the result of the task is ready.
This is what happens here:
At line 3, GetDataAsync will be called and executed in UI thread up to line 8.
At line 8 a task will be created and will run on thread pool thread and await is telling after running that task, the execution should continue in the previously captured context (Which is UI thread context).
An uncompleted task returns to the original caller (at line 3) which will be completed in future (after completing task of like 8 and then running line 9).
Then the Result method at line 3 will be executed, which blocks the task until it gets completed and final result of GetDataAsync is ready.
When the awaited task of line 8 completes, the scheduler tries to run line 9 in the UI thread, but the UI thread is blocked! So line 9 cannot be executed and GetDataAsync cannot be completed.
A deadlock happens: UI thread is waiting for GetDataAsync to complete, and GetDataAsync is waiting for main thread to be free to execute rest of the code.
To avoid the deadlock, instead of getting the result of async method by Wait or Result, you should use await. But as I mentioned earlier, in above scenario, if you as a library developer run your task (here Task.Delay) by ConfigureAwait(false) it prevents deadlock, because it tells not to come back to the original context after this line and continue execution on thread pool thread. So at line 8, it tells to continue in thread pool thread, so while the UI thread is blocked, but line 9 executes and returns data to UI thread and unblock it.
// UI code
1: private void button1_Click(object sender, EventArgs e)
2: {
3: var result = GetDataAsync().Result;
4: MessageBox.Show(result);
5: }
// A library code
6: public async Task<string> GetDataAsync()
7: {
8: await Task.Delay(1000).ConfigureAwait(false);
9: return "Data";
10: }
But again, keep in mind, as the UI developer, you should always use await for awaiting the Task and you should not use Result or Wait.
we cannot using the async /await keyword
Why not? Doing synchronous work will block the UI thread, which will degrade the user experience. It's almost always better to use async/await.
it "Tells" the task
Technically, it tells the await. This is a common mistake. The method is ConfigureAwait, not ConfigureTask.
it can resume itself on any available thread instead of waiting to to the main thread.
Technically, it just avoids the context that is normally captured by await. For a UI thread, this context would normally resume on the UI thread. ConfigureAwait(false) causes await to avoid that context and just resume as though there was no context, i.e., on a thread pool thread.
Its preventing the deadlock by free the UI for not waiting for the long process to be completed and task is not waiting for the main UI thread to be available.
No. The deadlock occurs because the await is waiting for the UI thread to be free and the UI thread is blocked on the async method to complete. ConfigureAwait(false) avoids the deadlock by allowing the await to resume on a thread pool thread instead of the UI thread. The UI thread is still blocked on the async method. The UI thread is not freed up to do other work, and the user experience is still degraded.
How eventually UI thread update UI after long proccess task has completed.
In that code sample, the UI thread blocks on the asynchronous code, so it will block (become unresponsive) while that code is running. When the code completes, the UI thread will keep executing, just like any other code. At the end of that method, it returns to its message queue proc, and the application is responsive again.
While there can technically be more than one UI thread, having an application with more than one UI thread is rare. And each UI component would belong to a specific UI thread; they can't be shared.

WebSphere WorkManager Cluster Double Execution of the Job

I have an Application deployed on WebSphere 8.5 with Java 1.7.1, defined with a cluster of 2 nodes.
In this application there is an EJB that, through a work manager submit an Async Job.
The problem is that on WAS 8.5 the Job is executed two times on both node of the cluster. In WAS 6.1 this did not happen.
The work is submitted by an Alarm Manager. Below the code extracted:
WorkManager wm = serviceLocator.getWorkManager("NameOfCustomWorkManager");
AsynchScope scope = wm.findAsynchScope("scopeName");
if (scope == null)
scope = wm.createAsynchScope("scopeName");
AlarmManager alarmManager = scope.getAlarmManager();
alarmManager.create(listener, "Alarm Context Info", (int) (DateUtils.getNextTime(nextTime) - System.currentTimeMillis())); --Fired on a certain hours
logger.info("Alarm fired.");
Somebody know if on was 8.5 there are additional configuration to avoid the problem described?
WorkManager in WebSphere Application Server, regardless of which version, does not have and has never had the ability to operate or coordinate across remote JVMs. The designed behavior of the WorkManager is that it is only able to run the work that you submit on the same JVM from where you submitted the work, and that it has no awareness of duplicate work that you submit from a different JVM and no mechanism for coordinating work across JVMs. The same is true of AlarmManager instances that you obtain from the WorkManager. (WebSphere Application Server actually has a way of accomplishing the above, which is the Scheduler, but the above code is not using that). Could it be possible that some earlier logic in the application that is impacted by the version change could be causing the Alarm to be created on both members now, whereas previously it would have only been created on one?

Xamarin.uitest how to close app instance

How to close and relaunch app in Xamarin.UI Test ? I want to restart app for each scenario in feature .
Platform: android
There is no quit() or close() session methods like we have in appium.
Calling ConfigureApp.Android.StartApp() in your test will launch a new session of your application for you to interact with (just make sure to save the new object).
However, with the use of NUnit, methods tagged with [Setup] will run automatically before every method tagged with[Test]. That means most test suites only use the ConfigureApp.Android.StartApp() method once, in [Setup].
Given you are on your are using Xamarin UI Test project,
You can use Finish() to close the application,
or
MoveTaskToBack(true) to minimize the application.
So that you can call them from your Test.cs, you'll need to write myBackdoorClose and myBackdoorMinimize functions (since Finish() and MoveTaskToBack(true) are only available in the App.cs context). How to do that, read here!
You can actually use Xamarin.UITest.ConfigureApp.Android.StartApp(AppDataMode.DoNotClear) in your test. It will close the app and restart it without clearing the app's data, all while the test keeps running.
This is a cross-platform solution; you can use Xamarin.UITest.ConfigureApp.iOS.StartApp... too.

How to give a web request to windows task Scheduler

I have a static webmethod i.e (http://localhost:61176/trunk/MusteriKontrol.aspx/CheckMusteri) I want to call this method from Windows Task Scheduler. How should I do this?
You could use a PowerShell script. This has a check for the time, a commented-out Try..Catch in case you want to do something if an error is raised from the query, and records when it has run in the Application event log:
# Download the HTML of a web page.
# Make sure an event log source is created with New-EventLog -LogName Application -Source MyPSscript
# Only do this if the time is 5a.m. or later, to give the server a rest from midnight.
$currHour = (Get-Date).Hour
if ($currHour -ge 5) {
$web = New-Object Net.WebClient
#try {
$temp = $web.DownloadString("http://localhost:61176/trunk/MusteriKontrol.aspx/CheckMusteri")
#}
#catch {
# do nothing.
#}
write-eventlog -logname Application -source MyPSscript -eventID 1001 -entrytype Information -message "Fetched web page." -category 0
}
Have considered a different alternative to scheduling the call of a web method from Windows Task Scheduler?
For example, scheduling tasks from within an ASP.NET project is possible using the Revalee open source project.
Revalee is a service that allows you to schedule web callbacks to your web application. In your case, you would schedule a callback that would call your web method at a specific time. Revalee works very well with tasks that are discrete transactional actions, like updating some database values or sending an automated email message (read: not long running). The upside is that the code that schedules the callback, as well as the code that performs your action (i.e., your web method), would all reside within your app.
To use Revalee, you would:
Install the Revalee Service, a Windows Service, on your server. The Windows Service is available in the source code (which you would compile yourself) or in a precompiled version available at the Revalee website.
Use the Revalee client library in your Visual Studio project. (There is an MVC-specific version too.) The client library is available in the source code (which, again, you would compile yourself) or in a precompiled version available via NuGet.
You would register a future callback when your code calls the ScheduleWebMethodCallback() method (this example is assuming that you need your action to run 12 hours from now).
private void ScheduleWebMethodCallback()
{
DateTimeOffset callbackTime = DateTimeOffset.Now.AddHours(12.0);
// The callback should be in 12 hours from now
Uri callbackUrl = new Uri(string.Format("http://localhost:61176/trunk/MusteriKontrol.aspx/CheckMusteri"));
// Register the callback request with the Revalee service
RevaleeRegistrar.ScheduleCallback(callbackTime, callbackUrl);
}
When Revalee calls your application back, your app would perform whatever action you have coded it to do in the web method you have listed above.
In case it was not clear above, the Revalee Service is not an external 3rd party online scheduler service, but instead a Windows Service that you install and fully control on your own network. It resides and runs on a server of your own choosing, most likely your web server (but this is not a requirement), where it can receive callback registration requests from your ASP.NET application.
I hope this helps.
Note: The code example above uses a synchronous version of ScheduleCallback(), the Revalee client library also supports asynchronous calls à la:
RevaleeRegistrar.ScheduleCallbackAsync(callbackTime, callbackUrl);
Disclaimer: I was one of the developers involved with the Revalee project. To be clear, however, Revalee is free, open source software. The source code is available on GitHub.

Resources