如何在WPF中的UserControl中运行BackgroundWorker?

时间:2016-05-30 07:34:19

标签: c# wpf

我在UserControl中运行BackgroundWorker时遇到问题,无法从服务器下载一些内容。我的问题是,当我编写以下代码时,UserControl get返回主窗体并且下载不会开始。

public AdFeeds()
        {
                InitializeComponent();
                bgWorker = new BackgroundWorker();
                bgWorker.DoWork += bgWorker_DoWork;
                bgWorker.RunWorkerAsync();
        }
 void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            DownloadWallpaper();
        }

下载壁纸我使用以下代码

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 
            {

            }
        }

我希望在初始化主表单时初始化该用户控件,所以我等到下载的用户控件的内容被锁定,直到内容被下载。

1 个答案:

答案 0 :(得分:2)

加载AdFeeds后运行事件。为此,请在Loaded事件处理程序中启动worker。

public AdFeeds()
{
    InitializeComponent();

    Loaded += OnLoaded;
}

private async void OnLoaded(object sender, RoutedEventArgs e)
{
    Loaded -= OnLoaded;

    await Task.Run(()=>
    {
        DownloadWallpaper();
    });
}   

此外,无需使用后台工作程序。您可以使用简单的Taskawait