2

I'm trying to read from a file asynchronously, and safely (minimum level of permissions sought). I'm using .NET 3.5 and cannot find a good example for this (all uses async and await).

 public string GetLines()
    {
        var encoding = new UnicodeEncoding();
        byte[] allText;
        using (FileStream stream =File.Open(_path, FileMode.Open))
        {
            allText = new byte[stream.Length];
            //something like this, but does not compile in .net 3.5
            stream.ReadAsync(allText, 0, (int) allText.Length);
        }
        return encoding.GetString(allText);
    }  

Question is, how do I do this asynchronously in .net 3.5, wait till the operation is finished and send back all lines to the caller?

The caller can wait till the operation is complete, but the read has to happen in a background thread.

The caller is a UI thread, and I'm using .NET 3.5

4

3 回答 3

3

有几种选择,但最简单的方法是让这个方法接受一个回调,然后在它计算出给定值时调用它。调用者需要传入回调方法来处理结果而不是阻塞方法调用:

public static void GetLines(Action<string> callback)
{
    var encoding = new UnicodeEncoding();
    byte[] allText;
    FileStream stream = File.Open(_path, FileMode.Open);
    allText = new byte[stream.Length];
    //something like this, but does not compile in .net 3.5
    stream.ReadAsync(allText, 0, (int)allText.Length);
    stream.BeginRead(allText, 0, allText.Length, result =>
    {
        callback(encoding.GetString(allText));
        stream.Dispose();
    }, null);
}
于 2013-09-13T16:37:08.327 回答
1

如果要等到操作完成,为什么需要异步进行呢?

return File.ReadAllText(_path, new UnicodeEncoding());

会做的伎俩

于 2013-09-13T16:36:55.730 回答
0

也许是这样的:

GetLines(string path, ()=>
{
    // here your code...
});

public void GetLines(string _path, Action<string> callback)
{
    var result = string.Empty;

    new Action(() =>
    {
        var encoding = new UnicodeEncoding();
        byte[] allText;
        using (FileStream stream = File.Open(_path, FileMode.Open))
        {
            allText = new byte[stream.Length];
            //something like this, but does not compile in .net 3.5
            stream.Read(allText, 0, (int)allText.Length);
        }
        result = encoding.GetString(allText);
    }).BeginInvoke(x => callback(result), null);
}
于 2013-09-13T16:43:50.247 回答