开发者

Blocking a Thread in .Net

I have a class that has purely static Methods and properties. I am calling an async method on the class "Load" that asks a web service for a chunk of data, which then fires an event that executes the return method, "LoadCompleted". I have no idea how long the call is going to take (the diffe开发者_StackOverflow中文版rence between calling the "Load" method, then the "LoadCompleted" getting called).

I would like to block the application from proceeding any further until the callback method has been raised (as the app will try and get stuff from this class, which isn't populated until the "LoadComplete" method sets the data). How would i go about doing this?


Blocking the main UI thread should be avoided with extreme prejudice.

I would use the BusyIndicator control from the Silverlight Toolkit:-

<UserControl x:Class="StackoverflowSpikes.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit">

    <toolkit:BusyIndicator x:Name="busyInd" >
        <Grid x:Name="LayoutRoot">
          <!-- The rest of your content -->
        </Grid>
    </toolkit:BusyIndicator>

</UserControl>

Before calling Load use:-

busyInd.IsBusy = true;

then on LoadComplete use:-

busyInd.IsBusy = false;

This will lock out user input on the UI without blocking the main thread and give the use some feedback as to why they can't click anything right now. You can supply your own content for the busy message using the BustContent property. Of course if you don't like the way it looks you can style it to your preference.

If you want to get all MVVM you can bind the IsBusy property to a VM property that indicates that the VM doesn't want anything changing right now.


You can use the ManualResetEvent class to block the main thread if you want. Just call the WaitOne method to block and call the Set method to unblock when the asyc web request completes. Just be aware that if you block your main UI thread, your entire application will become completely unresponsive.


You could consider setting the UI controls to disabled at the start. On load complete you could display your data and then enable the UI controls. No thread blocking is necessary with this approach.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜