Reputation: 508
I am using Task class in my app. This is NOT WPF application! The question is are there any possibilities of calling function from Task body on UI thread, like this:
var task = new Task(() => DoSmth(1));
task.Start();
public void DoSmth(int arg)
{
//smth
CallNotifFuncOnUIThread(() => Notify(1));
//smth ELSE
CallNotifFuncOnUIThread(() => Notify(2));//notify AGAIN
//smth ELSE
}
public void Notify(int arg)
{
progressBar1.Value = arg;
}
Or maybe there are other solutions of this problem? I know about BackgroundWorker class, but what about Tasks?
Upvotes: 0
Views: 1055
Reputation: 96
With windows Form and progressBar1 component on ityou can use TPL IProgress
interface for Task
.
private void Form1_Load(object sender, EventArgs e)
{
Progress<int> progress = new Progress<int>();
var task = Alg(progress);
progress.ProgressChanged += (s, i) => { UpdateProgress(i); };
task.Start();
}
public void Notify(int arg)
{
progressBar1.Value = arg;
}
public static Task Alg(IProgress<int> progress)
{
Task t = new Task
(
() =>
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
((IProgress<int>)progress).Report(i);
}
}
);
return t;
}
Upvotes: 0
Reputation: 7197
UI is usually STA see: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680112(v=vs.85).aspx
so in order to do something from none UI thread in the UI you need to inject somehow the msg into the thread see for example htis winform example:
http://weblogs.asp.net/justin_rogers/articles/126345.aspx
watever UI you are using you will need a similar system.
Upvotes: 0
Reputation: 45109
If you have a task you can start it on the gui thread by providing the correct scheduler:
Task.Factory.StartNew(() => DoSomethingOnGUI(), TaskScheduler.FromCurrentSynchronizationContext());
Upvotes: 1
Reputation: 16277
You can always call other methods inside your DoSth()
Dispatcher.Invoke(...);
Dispatcher.BeginInvoke(...);
You can also user Task.ContinueWith(...)
to do sth after the task is finished processing ...
Upvotes: 1