The dispatcher object is used to modify the UI from a thread or a Task
Below how to use a Task
Method 1
bool result ;
Task<bool> task = Task.Run<bool>(async () => await RefreshUIAsync());
str = task.Result;
public async Task<bool> RefreshUIAsync()
{
bool result;
result= await Task.Factory.StartNew(() => RefreshUI());
return result;
}
private string RefreshUI()
{
bool result;
try
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
{
string ImagePath="";
pictureBox1.Image = Image.FromFile(ImagePath);
.......
});
result=true;
}
catch (Exception ex)
{
result=false;
}
return result;
}
Method 2
RefreshUIAsync().Wait();
public async Task RefreshUIAsync()
{
await Task.Run(() => {
This.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
{
string ImagePath="";
pictureBox1.Image = Image.FromFile(ImagePath);
.......
});
});
}
And below how to use a Thread
Method 1
myThread = new Thread(() => ThreaRefreshUI());
myThread.Start();
private void ThreaRefreshUI()
{
try
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
{
string ImagePath="";
pictureBox1.Image = Image.FromFile(ImagePath);
.......
});
}
catch (Exception ex)
{
}
}
Method 2
Thread thread = new Thread(new ThreadStart(ThreaRefreshUI));
thread.Start();
public void ThreaRefreshUI()
{
try
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
{
string ImagePath="";
pictureBox1.Image = Image.FromFile(ImagePath);
.......
});
}
catch (Exception ex)
{
}
}
Method 3
Thread thread = new Thread(ThreaRefreshUI);
thread.Start();
public void ThreaRefreshUI()
{
try
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
{
string ImagePath="";
pictureBox1.Image = Image.FromFile(ImagePath);
.......
});
}
catch (Exception ex)
{
}
}