从子类访问主窗体

时间:2014-02-28 05:34:19

标签: c# winforms

对于我的C#程序,我创建了以下对象。

processurls processurls1 = new processurls();

创建后,我单击一个按钮启动执行的计时器:

private void timer2_Tick(object sender, EventArgs e)
{
    processurls1.pURLS(UrlList, URLCountOf, HTTP, label1, TotalURLS2, TotalURLS);
}

此计时器每500毫秒将触发我的processurls1对象的pURLS功能。 每次都会更新我的主要表单Label label1.text。 但我的问题是它只会更新标签一次,我的程序运行得非常笨重。什么是传递标签对象的安全方法&我的子类的picturebox对象在主窗体上正确更新而没有滞后?

public void pURLS(List<string> UrlListOf, int Count, Images HTTP, Label label1, int TotalURLS2, int TotalURLS)
{
    try
    {
        string WebResponse = HTTP.DoGET(UrlListOf[Count]);
        string pattern = "href=\"(.*?)\"";
        MatchCollection OtherURLS = Regex.Matches(WebResponse, pattern);
        for (int i = 0; i < OtherURLS.Count; i++)
        {

            Match HasHttp = Regex.Match(OtherURLS[i].Value, "http");
            if (HasHttp.Success)
            {
                string CleanedUp = Regex.Replace(OtherURLS[i].Value, "href=\"", "");
                CleanedUp = Regex.Replace(CleanedUp, "\"", "");

                UrlListOf.Add(CleanedUp);
                TotalURLS2++;
            }
            else
            {
                string CleanedUp = Regex.Replace(OtherURLS[i].Value, "href=\"", "");
                CleanedUp = Regex.Replace(CleanedUp, "\"", "");
                CleanedUp = UrlListOf[TotalURLS2] + "" + CleanedUp;
                UrlListOf.Add(CleanedUp);
                TotalURLS2++;
            }
        }

        label1.Text = "U:" + TotalURLS2.ToString();
    }
    catch (Exception)
    {
    }
}

2 个答案:

答案 0 :(得分:0)

您需要学习异步基础。

也许500毫秒不足以获取/数据。而不是使用计时器,只需使用具有xx ms睡眠的异步任务

在您的MainForm上

public async Task UpdateMyLabels()
{
  while (true) //change here by something more reliant
  {
       await processurls1.pURLS(UrlList, URLCountOf, HTTP, label1, TotalURLS2, TotalURLS);
       Thread.Sleep(200); //ajust value here
  }
}

在“表格加载”事件中:

{
       UpdateMyLabels();
}

最后,在pUrls上添加“async”关键字:

public async Task pURLS

答案 1 :(得分:0)

将我的所有变量移动到类本身。现在我可以从我的backgroundworker访问一个属性并更新主窗体:D

    static int ImageCount = 0;
    static int currentImage = 0;
    Images HTTP = new Images();
    List<string> UrlList;
    static List<string> ImageCollection = new List<string>();

    public List<string> Images
    {
        get
        {
            return ImageCollection;
        }
        set
        {
            ImageCollection = value;
        }
    }

    public int CurrentImage
    {

        get
        {
            return currentImage;
        }
        set
        {
            currentImage = value;
        }
    }
    public int Count
    {
        get
        {
            return ImageCount;
        }
        set
        {
            ImageCount = value;
        }
    }

    public List<string> URLS
    {
        get
        {
            return UrlList;
        }
        set
        {
            UrlList = value;
        }
    }