Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#委托从类设置窗体控件_C#_Winforms_Asynchronous - Fatal编程技术网

C#委托从类设置窗体控件

C#委托从类设置窗体控件,c#,winforms,asynchronous,C#,Winforms,Asynchronous,我有一个表单(myForm)来实例化一个类(myClass)。在myClass中,我异步读取plc。异步读取使用两种方法,myClass.BeginRead和myClass.OnAsyncReadComplete。myItem.BeginRead接受一个异步回调和一个名为myItem的对象。当OnAsyncReadComplete触发时,我需要调用myForm中的一个方法来设置textbox控件的文本。我特别需要帮助连接一个委托,以设置返回myForm的控件。我计划使用if invoke req

我有一个表单(myForm)来实例化一个类(myClass)。在myClass中,我异步读取plc。异步读取使用两种方法,myClass.BeginRead和myClass.OnAsyncReadComplete。myItem.BeginRead接受一个异步回调和一个名为myItem的对象。当OnAsyncReadComplete触发时,我需要调用myForm中的一个方法来设置textbox控件的文本。我特别需要帮助连接一个委托,以设置返回myForm的控件。我计划使用if invoke required来设置textbox.text属性。 我已经包括了myClass中两个方法的示例

public void ReadPLCAsyc()
{
    AsyncCallback asyncCallback = new AsyncCallback(this.OnAsyncReadComplete);
    Result[] result;
    Item[] itemArray = null;

    this.myItem = null;
    this.myItem = new ABLogix.Item(Config.ReadAppSettingsByKey("PLC_Tagname"));
    this.myItem.Elements = 7;

    this.myItem.HWTagName = Config.ReadAppSettingsByKey("PLC_Tagname");
    this.myGroup.Items.Add(this.myItem);

    this.myDevice.TimeoutTransaction = 2000;
    itemArray = new AutomatedSolutions.Win.Comm.AB.Logix.Item[this.myDevice.Groups[0].Items.Count];
    this.myDevice.Groups[0].Items.CopyTo(itemArray, 0);
    this.myDevice.BeginRead(itemArray, out result, new AsyncCallback(this.OnAsyncReadComplete), this.myDevice);
}

public void OnAsyncReadComplete(IAsyncResult ar)
{

    Device d = (Device)ar.AsyncState;
    Result[] results;
    try
    {
        d.EndRead(out results, ar);
        var v = d.Groups[0].Items[0].Values;

        **//Need to set myForm.textbox1.text = v.ToString();**

    }
    catch (Exception ex)
    {

    }
}
使用此模式:

private void DoSomething()
{
    if(YourControl.InvokeRequired)
    {
        YourControl.BeginInvoke(new Action(DoSomething));
        return;
    }
    YourControl.Property=Value;
}

“MyDevice”是什么类别?MyDevice是用于与plc通信的控件的一部分。不确定这是否回答了你的问题??你有这门课的文档吗?至少有可用的方法?我认为你可以使用async Wait来简化你的生活,或者干脆
YourControl.BeginInvoke(DoSomething)@PhilippeParé如果您将DoSomething作为BeginInvoke的参数传递,则将出现错误:无法从“方法组”转换为“系统.Delegate”。因为BeginInvoke需要委托作为参数,所以我认为传递新操作(DoSomething)是传递参数最简单、最干净的方法。你说得对!很抱歉,BeginInvoke采取了行动