I have AuthenticateWindow
and MainWindow
, markup and code is exposed below. It is very simplified. When in the MainWindow
constructor I use Thread
class it works fine, but if I use Task
class, UI is suspended, that is 'MainWindow' is not shown while Thread.Sleep(5000);
is elapsed. Is it possible to use Task
class (because I need its cancellation mechanism and Status
property) without any UI suspending?
Important condition: I cannot fix code in AuthWindow
.
AuthenticateWindow:
xaml
<Grid>
<Button Content="OpenMainWindow"
Click="ButtonBase_OnClick"></Button>
</Grid>
c#
public partial class AuthWindow : Window
{
public AuthWindow()
{
InitializeComponent();
}
private void DoAbsolutelyNothing()
{
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(DoAbsolutelyNothing).ContinueWith(t =>
{
var window = new MainWindow();
if (window.IsInitialized)
window.Show();
Close();
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
MainWindow:
xaml
<Grid>
<TextBlock Text="MainWindow"></TextBlock>
</Grid>
c#
public partial class MainWindow : Window
{
private Task _task;
private void TestMethod()
{
Thread.Sleep(5000);
Debug.WriteLine("TestMethod comleted");
}
public MainWindow()
{
InitializeComponent();
// it works badly
//_task = Task.Factory.StartNew(TestMethod);
// it works fine
new Thread(TestMethod).Start();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
}
}
Windows 7, .Net 4.0
Important: Exposed code reproduces the problem, just copy-paste!