简体   繁体   中英

EventHandler vs Timeout

I had write a little application on c# to reading some plc data by using ethernet protocol. Ethernet socket, open and close are stored inside a .dll library. Now, i using this public method:

    public static string readdata()
    {
      try
      {
        ...
        return (plcdata());
      }
      catch
      {}
    }

My doubt: if the plcdata() (that is a method of a .dll) waiting a few second (for istance slow comunication ...) my application may be frozen.

So, i try to add a EventHandler on string returned like this:

    private static TextBox auxDataTextBox = new TextBox();

    public static void goRead()
    {            
        auxDataTextBox.TextChanged += new EventHandler(auxDataIncoming);
        auxDataTextBox.Text = plcdata();
    }

    private static void auxDataIncoming(object sender, EventArgs e)
    {      
        // Do something
    }

In this case when the "plcdata()" changed, the auxDataIncoming will be raise. It is correct? Or is better make a timeout control? Or make new thread?

Thanks a lot for yours opinion

Your change won't make a difference, it' still all running on the UI thread. To make plcdata() a non-blocking call you would need to fire it off on another thread eg

private static TextBox auxDataTextBox = new TextBox();

public static void goRead()
{            
    auxDataTextBox.TextChanged += new EventHandler(auxDataIncoming);
    Task.Factory.StartNew(() => { 
        return plcData(); 
    }).ContinueWith(task => {
        auxDataTextBox.Text = task.Result;
    }, null, TaskContinuationOptions.NotOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
}


private static void auxDataIncoming(object sender, EventArgs e)
{      
    // Do something
}

This will not unfreeze your application. The effect will be exactly the same. This is because you are still running the plcdata on your UI thread.

The whole event structure you set up does not make sense at all.

You should look into multithreading. A very easy way to do this is using a BackgroundWorker .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM