Reputation: 1042
I am having problem in running BackgroundWorker in UserControl for downloading some content from server. My problem is this that when I write the following code the UserControl get returns to main form and downloading does not get started.
public AdFeeds()
{
InitializeComponent();
bgWorker = new BackgroundWorker();
bgWorker.DoWork += bgWorker_DoWork;
bgWorker.RunWorkerAsync();
}
void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
DownloadWallpaper();
}
For downloading wallpaper I am using the following code
public static void DownloadWallpaper()
{
try
{
DataSet dsFile = Global.ReadConfig;
XDocument xDoc = XDocument.Load(dsFile.Tables[0].Rows[0][9].ToString());//Environment.CurrentDirectory+@"..\..\..\App_Data\Wallpaper.xml");//(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Wallpaper\\Themes.xml");
string s = xDoc.Root.Name.ToString();
var countNode = xDoc.Root.Elements().Count();
for (int i = 0; i < countNode; i++)
{
XNode childNode = xDoc.Root.Nodes().ElementAt(i);
XElement ele = (XElement)childNode;
path = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Wallpaper\\Banner\\" + ele.Name;
DirectoryInfo di = Directory.CreateDirectory(path);
var movieList = from a in xDoc.Root.Descendants(ele.Name).Elements()
select new Ad()
{
Path = ele.Name.ToString(),
Link = a.Value
};
foreach (var a in movieList)
{
Global.filedownload(dsFile.Tables[0].Rows[0][1].ToString() + "/Banner/" + ele.Name + "/", path + "\\");
advertisement.Add(a);
}
}
}
catch
{
}
}
I want that user control to be initialized when the main form is initialized so I wait till the content of the user control downloaded my UI is getting locked till the content gets downloaded.
Upvotes: 2
Views: 929
Reputation: 17402
Run the event after AdFeeds
has been loaded. To do this, start the worker in the Loaded
event handler.
public AdFeeds()
{
InitializeComponent();
Loaded += OnLoaded;
}
private async void OnLoaded(object sender, RoutedEventArgs e)
{
Loaded -= OnLoaded;
await Task.Run(()=>
{
DownloadWallpaper();
});
}
Also, no need to use a Background worker. You can just use a simple Task
, and await
it.
Upvotes: 2