WPF Application freezes for 20 seconds - wpf

I have a WPF (MVVM with Prism) application
There are quite a lot of factors that can affect this problem, but I will try to boil it down.
Hopefully I can at least get some tips how to trouble shoot this.
I have a user control containing a datagrid and a typical Search-button. The grid is initially empty and on SearchCommand. The user control uses a class "AccountServiceGateway" (_accountSG below) to make a request to the server, and then fills datasource of the grid with the result. Pretty standard.
VM: Binding command to handler in ctor
...
SearchCommand = new DelegateCommand(async () => await SearchOnServer(new AccountFilterDTO()));
VM, Button handler implementation
private async Task<bool> SearchOnServer(AccountFilterDTO filter)
{
var searchAccountResults = await _accountSG.SearchAccounts(filter);
//AccountSearchResultList is an observable collection that is datasource for the grid
AccountSearchResultList = new ObservableCollection<AccountSearchResultDTO>(searchAccountResults);
}
// Account Service gateway, making a web request
protected async Task<T> GetFromUrl<T>(string urlPart)
{
...
var response = await _httpClient.GetAsync(url);
resStr = await response.Content.ReadAsStringAsync();
//convert to T and return
}
EDIT
When I replace the implementation of GetFromUrl() with
await Task.Delay(5000)
return [hardcoded list of T]
everything works ok (although the hardcoded list is only 5 items)
END EDIT
Now to my problem. Getting an answer from the server taks about 1-2secs, as expected. I can follow the code until my datasource is filled. But then the GUI freezes for roughly (10-)20 seconds before anything is displayed, then efter the freeze, everything is as expected.
Other things to notice is that user control is in a Prism-region, within a Telerik RadTabbedWindow, so if this looks ok ith might be something else.
So my main question is, why does it hang for 20 seconds, I suspect there is some threading problem, but if it where a deadlock, wouldnt it hang forever? Any way to trouble shoot this?

Has the view changed in some way so that list virtualisation has been effectively turned off?
eg. Parent ScrollerViewer been added

Related

MessageBox.Show causing blocking after close on Windows 10 tablet

We have a WPF app that also runs on a tablet. We are targeting Windows 10, .Net 4.6.2.
We have an async event handler that calls MessageBox.Show. The user clicks Yes and the app continues on doing some stuff.
When the app runs on tablet hardware, the app locks up for 10-20 seconds after the event completes. I cannot duplicate this from the desktop or in the simulator, only when it actually runs on the tablet.
I have isolated it to the MessageBox. When I take it out the app behaves normally. I feel like maybe it has something to do with threading.
Any ideas?
using "async" will cause the MesssageBox.Show() method to be called on a separate thread. instead of putting the MesssageBox.Show() call in an async call consider putting it in a Thread, ensuring you declare it a background thread:
Thread messageBoxThread = new Thread(() => { yourMessageBoxCall(); );
messageBoxThread.IsBackground = true;
messageBoxThread.Start();
Based on #stuicidle's clue, I went down a better research path. Many people have tried to solve the async MessageBox problem.
I ultimately got my solution from how can i use Messagebox.Show in async method on Windows Phone 8?
My code looks like this:
private async Task HandleEvent()
{
var message = $"Continue?";
MessageBoxResult result = MessageBoxResult.None;
var dg = new Action(() => result = MessageBox.Show(message, "Warning", MessageBoxButton.YesNo));
await Dispatcher.BeginInvoke(dg);
if (result == MessageBoxResult.Yes)
await DoSomeStuff();
}

WPF with UI threading issues - TaskFactory, CollectionView issues - syntax nightmare

See bottom of post for my pseudo solution.
Once again I'm completely and utterly stuck on this. I've burned hours trying to understand - and yes I can get a single collectionviewsource to work beautifully with nothing about threading on the code behind.
Imagine my shock when I found merely adding two collectionviewsources on the page causes threading issues. I've spent a few hours last night reading Async in C#5 and the MSDN stuff however I get into work today and I can't decipher how to make this happen.
The code below is the last attempt I've made before whining for help as I've burnt, possibly, a bit too much work time on attempting to understand how to do this. I understand that I need one collectionviewsource to complete before starting the other, so I tried Await Task.ContinueWith etc to try and chain one after the other.
Lining up both sets of tasks in the threads correctly seems to be quite tricky, or I'm still misunderstanding something fundemental.
If anyone can advise how they would asynchronously populate a few controls on a WPF UI I would be very grateful.
The application itself is a throwaway application, linked to an Access database that I'm using to try and become fluent enough in threading to implement it in our proper code base. I'm long way off that!
Updated with more complete code samples and the adjustments made according to answers:
Private Async Sub MainWindowLoaded(sender As Object, e As RoutedEventArgs) Handles MyBase.Loaded
InitializeComponent()
Dim personSetViewSource As System.Windows.Data.CollectionViewSource = CType(Me.FindResource("personSetViewSource"), System.Windows.Data.CollectionViewSource)
Dim contactSetViewSource As System.Windows.Data.CollectionViewSource = CType(Me.FindResource("contactSetViewSource"), System.Windows.Data.CollectionViewSource)
Dim personList = Await Task.Run(Function() personSet.personList)
personSetViewSource.Source = personList
Dim contactList = Await Task.Run(Function() contactSet.contactList)
contactSetViewSource.Source = contactList
End Sub`
The ObservableCollectionEx class:
public class ObservableCollectionEx<T> : ObservableCollection<T>
{
public override event NotifyCollectionChangedEventHandler CollectionChanged;
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
using (BlockReentrancy())
{
NotifyCollectionChangedEventHandler collectionChanged = this.CollectionChanged;
if (collectionChanged != null)
foreach (NotifyCollectionChangedEventHandler nh in collectionChanged.GetInvocationList())
{
DispatcherObject dispObj = nh.Target as DispatcherObject;
if (dispObj != null)
{
Dispatcher dispatcher = dispObj.Dispatcher;
if (dispatcher != null && !dispatcher.CheckAccess())
{
NotifyCollectionChangedEventHandler nh1 = nh;
dispatcher.BeginInvoke(
(Action) (() => nh1.Invoke(this,
new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Reset))),
DispatcherPriority.DataBind);
continue;
}
}
nh.Invoke(this, e);
}
}
}
}
Please note, I can't translate this class to VB due to requiring an Event Override.
Another variation I've tried, but falls foul of thread ownership again. The two collectionviews thing isn't yielding to a solution: I don't know if it's because the underlying collection isn't good for it or whether in reality it wasn't meant to work that way. I get close but no cigar.
Dim CarePlanList = Task.Run(Function() CarePlanSet.CarePlanList)
Dim rcpdList = Task.Run(Function() rcpdSet.rcpdList)
Dim tasks() As Task = {CarePlanList, rcpdList}
Dim t = New TaskFactory
Await t.ContinueWhenAll(tasks, Sub()
carePlanSetViewSource.Source = CarePlanList
rcpdSetViewSource.Source = rcpdList
End Sub)
I found a way to do it, based on a combination of feedback and research this morning. Building the two collectionviews asynchronously itself is somewhat impractical given the STAThread model of WPF. However, merely ensuring one HAS completed and shifting some of the async out of one entity class has made this plausible.
Instead I fire off the first task, who's underlying class does build it's data with its own Async method. Then test to see if it has completed before allowing the second collectionview to be fired off. This way I don't need to worry about context or dispatcherobjects. The second collection does not use any async.
Dim personList = Task(Of List(Of person)).Run(Function() personSet.personList)
Dim contactList = Task(Of ObservableCollectionEx(Of contact)).Run(Function() contactSet.contactList)
contactSetViewSource.Source = contactList.Result
If contactList.IsCompleted Then personSetViewSource.Source = personList.Result
This is an experimental project for concept research really. As it happens, the idea I'd want two such lists built this way isn't as useful as all that but I do see where being able to compose a data heavy interface asynchronously could be handy.
Your two code samples each have issues that jump out right away.
In the first you are awaiting task1, I assume with more code following, but all task1 is doing is starting what is basically a fire and forget operation back to the UI thread (Dispatcher.BeginInvoke), therefore not really producing anything asynchronous to await.
In the second, the primary issue seems to be that you are doing a lot of setup of Task instances and chaining them with continuations but never starting the action2 Task, which appears to be the root of the whole chain, hence getting no activity at all. This is similar to what you get with a BackgroundWorker that never has RunWorkerAsync called.
To get this working properly and avoid making your head spin any more I would suggest starting by writing this whole block without any async and verifying that everything loads as expected, but with the UI lockup you want to avoid. Async/Await is designed to be added into code like that with minimal structural changes. Using Task.Run along with async and await you can then make the code asynchronous.
Here's some pseudocode for the basic pattern, without async to start:
PersonSetList = LoadData1()
CVS1.Source = PersonSetList
ContactList = LoadData2()
CVS2.Source = ContactList
and now adding async:
PersonSetList = await Task.Run(LoadData1())
CVS1.Source = PersonSetList
ContactList = await Task.Run(LoadData2())
CVS2.Source = ContactList
What this will now do is start a task to load the person data and immediately return from your WindowLoaded method, allow the UI to continue rendering. When that data is loaded it will continue to the next line on the original thread and push the data into the UI (which may itself slow down the UI while rendering). After that it will do the same for the Contact data. Notice that Dispatcher isn't needed explicitly because await is returning back to the UI thread for you to complete its continuation.

Replacing methods that use backgroundworker to async / tpl (.NET 4.0)

My questions are many. Since I saw. NET 4.5, I was very impressed. Unfortunately all my projects are .NET 4.0 and I am not thinking about migrating. So I would like to simplify my code.
Currently, most of my code that usually take enough time to freeze the screen, I do the following:
BackgroundWorker bd = new BackgroundWorker();
bd.DoWork += (a, r) =>
{
r.Result = ProcessMethod(r.Argument);
};
bd.RunWorkerCompleted += (a, r) =>
{
UpdateView(r.Result);
};
bd.RunWorkerAsync(args);
Honestly, I'm tired of it. And that becomes a big problem when there is a logic complex user interaction.
I wonder, how to simplify this logic? (Remember that I'm with. Net 4.0) I noticed a few things by google, but not found anything easy to implement and suitable for my needs.
I thought this solution below:
var foo = args as Foo;
var result = AsyncHelper.CustomInvoke<Foo>(ProcessMethod, foo);
UpdateView(result);
public static class AsyncHelper
{
public static T CustomInvoke<T>(Func<T, T> func, T param) where T : class
{
T result = null;
DispatcherFrame frame = new DispatcherFrame();
Task.Factory.StartNew(() =>
{
result = func(param);
frame.Continue = false;
});
Dispatcher.PushFrame(frame);
return result;
}
}
I am not sure about the impact is on manipulating the dispatcher frame.
But I know That it would work very well, for example, I could use it in all the events of controls without bothering to freeze the screen.
My knowledge about generic types, covariance, contravariance is limited, maybe this code can be improved.
I thought of other things using Task.Factory.StartNew and Dispatcher.Invoke, but nothing that seems interesting and simple to use. Can anyone give me some light?
You should just use the Task Parallel Library (TPL). The key is specifying the TaskScheduler for the current SynchronizationContext for any continuations in which you update the UI. For example:
Task.Factory.StartNew(() =>
{
return ProcessMethod(yourArgument);
})
.ContinueWith(antecedent =>
{
UpdateView(antecedent.Result);
},
TaskScheduler.FromCurrentSynchronizationContext());
Aside from some exception handling when accessing the antecedent's Result property, that's all there is too it. By using FromCurrentSynchronizationContext() the ambient SynchronizationContext that comes from WPF (i.e. the DispatcherSynchronizationContext) will be used to execute the continuation. This is the same as calling Dispatcher.[Begin]Invoke, but you are completely abstracted from it.
If you wanted to get even "cleaner", if you control ProcessMethod I would actually rewrite that to return a Task and let it own how that gets spun up (can still use StartNew internally). That way you abstract the caller from the async execution decisions that ProcessMethod might want to make on its own and instead they only have to worry about chaining on a continuation to wait for the result.
UPDATE 5/22/2013
It should be noted that with the advent of .NET 4.5 and the async language support in C# this prescribed technique is outdated and you can simply rely on those features to execute a specific task using await Task.Run and then execution after that will take place on the Dispatcher thread again automagically. So something like this:
MyResultType processingResult = await Task.Run(() =>
{
return ProcessMethod(yourArgument);
});
UpdateView(processingResult);
How about encapsulating the code that is always the same in a reusable component? You could create a Freezable which implements ICommand, exposes a property of Type DoWorkEventHandler and a Result property. On ICommand.Executed, it would create a BackgroundWorker and wire up the delegates for DoWork and Completed, using the value of the DoWorkEventHandler as event handler, and handling Completed in a way that it sets its own Result property to the result returned in the event.
You'd configure the component in XAML, using a converter to bind the DoWorkEventHandler property to a method on the ViewModel (I assume you've got one), and bind your View to the component's Result property, so it gets updated automatically when Result does a change notification.
The advantages of this solution are: it is reusable, and it works with XAML only, so no more glue code in your ViewModel just for handling BackgroundWorkers. If you don't need your background process to report progress, it could even be unaware that it runs on a background thread, so you can decide in the XAML whether you want to call a method synchronously or asynchronously.
A few months have passed, but could this help you?
Using async/await without .NET Framework 4.5

WPF issue with updating

I have a strange issue. I wonder whether it's a standard behavior of the .NET components, and how to handle this.
Our app is using galasoft mvvm light. I have a form with a tree view, which is getting the data via an asynchronous call. And why that asynchronous task is running, we're showing a progress bar to the user. I'm using ObservableCollection as a collection for my tree structure. Now the problem:
This piece of code gives us the info:
public Task<ObservableCollection<FillingTreeNode>> GetTreeStructureAsync(SyncSettings settings)
{
SearchRequest request = BuildRequest();
return searchService.SearchRecordsAsync(request).ContinueWithConversion(
records => new ObservableCollection<FillingTreeNode>(records
.Select(cabinet => new FillingTreeNode
{
IsChecked = false,
DisplayName = cabinet.Fields[Fields.CabinetName].Value,
Node = cabinet.AsFillingNode(FillingNodeType.Cabinet),
NumberOfNodes = SendXmlRequest(record),
Children = new ObservableCollection<FillingTreeNode>(GetChildren (record));
}
}
This is the task extension to convert the result to some new type:
public static Task<TNew> ContinueWithConversion<TOld, TNew>(this Task<TOld> task, Func<TOld, TNew> conversionAction)
{
return task.ContinueWith(completedTask => conversionAction(task.Result));
}
Now the issue. The data is loaded from the server, the UI (the progress bar) says that the data is loaded, and only after that SendXmlRequest(record) (which is a bit long to wait) begins to work! But i expect that it's already done. The user sees nothing until those functions are finished working
Do you know what is the cause of the problem? Can that be the behavior of the Observable collection? How can i fix it?
Thank in advance.

Silverlight HttpWebRequest.Create hangs inside async block

I am trying to prototype a Rpc Call to a JBOSS webserver from Silverlight (4). I have written the code and it is working in a console application - so I know that Jboss is responding to the web request. Porting it to silverlight 4, is causing issues:
let uri = new Uri(queryUrl)
// this is the line that hangs
let request : HttpWebRequest = downcast WebRequest.Create(uri)
request.Method <- httpMethod;
request.ContentType <- contentType
It may be a sandbox issue, as my silverlight is being served off of my file system and the Uri is a reference to the localhost - though I am not even getting an exception. Thoughts?
Thx
UPDATE 1
I created a new project and ported my code over and now it is working; something must be unstable w/ regard to the F# Silverlight integration still. Still would appreciate thoughts on debugging the "hanging" web create in the old model...
UPDATE 2
let uri = Uri("http://localhost./portal/main?isSecure=IbongAdarnaNiFranciscoBalagtas")
// this WebRequest.Create works fine
let req : HttpWebRequest = downcast WebRequest.Create(uri)
let Login = async {
let uri = new Uri("http://localhost/portal/main?isSecure=IbongAdarnaNiFranciscoBalagtas")
// code hangs on this WebRequest.Create
let request : HttpWebRequest = downcast WebRequest.Create(uri)
return request
}
Login |> Async.RunSynchronously
I must be missing something; the Async block works fine in the console app - is it not allowed in the Silverlight App?
(Thanks for sending this to fsbugs, to force us to take a hard look.)
The problem is Async.RunSynchronously. When called on the UI thread, this blocks the UI thread. And it turns out that WebRequest.Create() on Silverlight dispatches to the UI thread. So it is a deadlock.
In general, try to avoid Async.RunSynchronously on Silverlight (or on any UI thread). You can use Async.StartImmediate in this example. Alternatively, I think you can call RunSynchronously from any background thread without issues. (I have not tried enough end-to-end Silverlight scenarios myself to offer more advice as yet. You might check out
Game programming in F# (with Silverlight and WPF)
F# and Silverlight
F# async on the client side
for a few short examples.)
(In retrospect, the F# design team thinks that we maybe should not have included Async.RunSynchronously in FSharp.Core for Silverlight; the method potentially violates the spirit of the platform (no blocking calls). It's possible we'll deprecate that method in future Silverlight releases. On the other hand, it still does have valid uses for CPU-intensive parallelism on Silverlight, e.g. running a bunch on (non-IO) code in parallel on background threads.)
Seems like a similar issue here - though no reference to silverlight (in fact it is a "windows service class"):
http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/10854fc4-2149-41e2-b315-c533586bb65d
I had similar problem. I was making a Silverlight MVVM ViewModel to bind data from web.
Don Syme commented himself:
I’m not a data-binding expert, but I
believe you can’t “hide” the asyncness
of a view model like this for WPF and
Silverlight. I think you would need to
expose Task, Async or an
observable collection. AFAIK the only
way to get Silverlight and WPF to bind
asynchronously to a property is if it
is an observable collection.
Anyway, I installed F# Power Pack to get AsyncReadToEnd.
It didn't solve the case... I added domains to trusted sites but it didn't help... Then I added a MySolution.Web -asp.net-site and clientaccesspolicy.xml. I don't know if those had any effect.
Now, with Async.StartImmediate I got web service call working:
let mutable callresult = ""
//let event = new Event<string>()
//let eventvalue = event.Publish
let internal fetch (url : Uri) trigger =
let req = WebRequest.CreateHttp url
//req.CookieContainer <- new CookieContainer()
let asynccall =
async{
try
let! res = req.AsyncGetResponse()
use stream = res.GetResponseStream()
use reader = new StreamReader(stream)
let! txt = reader.AsyncReadToEnd()
//event.Trigger(txt)
callresult <- txt //I had some processing here...
trigger "" |> ignore
with
| :? System.Exception as ex ->
failwith(ex.ToString()) //just for debug
}
asynccall |> Async.StartImmediate
Now I will need my ViewModel to listen the mutable callresult.
In your case you need also a crossdomain.xml to the server.
The trigger is needed to use the UI-thread:
let trigger _ =
let update _ = x.myViewModelProperty <- callresult
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(new Action(update)) |> ignore
fetch serviceUrl trigger
I think you are hitting the maximum http connections restriction: see Aynchronous web server calls in Silverlight and maximum HTTP connections and http://weblogs.asp.net/mschwarz/archive/2008/07/21/internet-explorer-8-and-maximum-concurrent-connections.aspx

Resources