永发信息网

如何异步读取文件

答案:2  悬赏:80  手机版
解决时间 2021-03-10 20:46
  • 提问者网友:战魂
  • 2021-03-10 11:22
如何异步读取文件
最佳答案
  • 五星知识达人网友:鸠书
  • 2021-03-10 12:42
异步读取文件,读取完成之后触发事件,通知主线程。主线程与读取文件的线程互相独立。
全部回答
  • 1楼网友:鸠书
  • 2021-03-10 13:07

public delegate void mydelegatefile(byte[] bb);

public class readfilestate

    {

    public  filestream fs;

    public  byte[] bytefile;

    public int bytenum;

    }

    /// <summary>

    /// 打开一个文本文件,显示在richtextbox中

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    private void o_fs_click(object sender, eventargs e)

    {

    string s = "";

    ofd.filter = "文本文件|*.txt|全部文件|*.*";

        ofd.defaultext = "txt";

    ofd.filename = "";

    try

    {

    if (ofd.showdialog() == dialogresult.ok)

    {

    s = ofd.filename;

    fs = new filestream(s,filemode.open,fileaccess.read);

    readfilestate rfs = new readfilestate();

    rfs.bytefile = new byte[fs.length];

    rfs.fs = fs;

    rfs.bytenum = (int)fs.length;

    asynccallback ac = new asynccallback(getfileresult);

    fs.beginread(rfs.bytefile, 0, (int)fs.length, ac, rfs);

    }

    }

    catch (ioexception iex)

    {

    messagebox.show(iex.message);

    }

    }

    void getfileresult(iasyncresult iar)

    {

    try

    {

    thread.sleep(5000);

    readfilestate rfs = (readfilestate)iar.asyncstate;

    if (rfs != null)

    {

    filestream fs = rfs.fs;

    int n = fs.endread(iar);

    if (rfs.bytefile != null)

    {

    this.invoke(mdd, rfs.bytefile);

    }

    else { messagebox.show("当前数组值为空."); }

      }

    }

    catch (ioexception iex)

    {

    messagebox.show(iex.message);

    }

    finally

    {

    fs.close();

    }

    }

    void showfile(byte[] y)

    {

     //string s = "";

    //for (int i = 0; i < y.getlength(0); ++i)

    //{

    //    s = s + y[i].tostring()+" ";

    //}

    string ss = encoding.getencoding(936).getstring(y);

    rtb.text = ss;

    //rtb.text ="读取文件字符串的长度是:"+ i.tostring();

    }

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯