I have a method with the following code:
object frm = null;
// shows the overlay loading mask
Core.ShowLoadingMask("Please wait...");
// start task
Task.Factory.StartNew(() => {
// go to server and get the data
var employee = new Data.Entities.Employee(employeeId);
// instantiate the class type (reflection)
frm = Activator.CreateInstance(type, employee );
}).ContinueWith((task) => {
// hide loading mas
Core.HideLoadingMask();
if (frm != null) this.Panel.Controls.Add(frm);
});
So, how can I force that the code inside ContinueWith()
force to use the Current Thread, or maybe I'm doing it wrong.
The process I need is:
Any clue?
Pass TaskScheduler.FromCurrentSynchronizationContext()
to ContinueWith()
...
.ContinueWith((task) => {
// hide loading mas
Core.HideLoadingMask();
if (frm != null) this.Panel.Controls.Add(frm);
}, TaskScheduler.FromCurrentSynchronizationContext());
Assuming that this
is also a UI control, you can store the current dispatcher using this.Dispatcher
before starting the task. Then in the ContinueWith
, use the stored dispatcher to execute the hide operation. See Dispatcher.BeginInvoke .
Dispatcher dispatcher = this.Dispatcher;
Core.ShowLoadingMask("Please wait...");
return Task.Factory.StartNew(() =>
{
doStuff();
frm = ...
}).ContinueWith(t =>
{
dispatcher.BeginInvoke(new Action(() =>
{
Core.HideLoadingMask();
if (frm != null) this.Panel.Controls.Add(frm);
}));
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.