小编Mid*_*das的帖子

在"using"语句中使用yield时,何时发生Dispose?

我有一个关于延期执行和数据处理的问题.

请考虑以下示例:

private IEnumerable<string> ParseFile(string fileName)
{
    using(StreamReader sr = new StreamReader(fileName))
    {
        string line;
        while((line = sr.ReadLine()) != null)
        {
            yield return line;
        }
    }
}

private void LineReader(string fileName)
{
    int counter = 0;

    foreach(string line in ParseFile(fileName))
    {
        if(counter == 2)
        {
            break; // will this cause a dispose on the StreamReader?
        } else
        {
            Console.WriteLine(line);
            counter++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请问break声明立即引起读者ParseFile处置,或者它仍然在上下文中考虑,并锁定该文件打开,直到程序本身被关闭?

c# file-io using deferred-execution

21
推荐指数
1
解决办法
1877
查看次数

将async/await与Result混合

让我先简单介绍一下这个问题:

  1. 我已经阅读了几个SO问题,说你不应该这样做(比如如何安全地混合同步和异步代码)
  2. 我已经读过Async/Await - 异步编程中的最佳实践再次说你不应该这样做

所以我知道这不是最佳做法,也不需要任何人告诉我这样做.这更像是"为什么这个工作"的问题.

有了这个,这是我的问题:

我写了一个小的GUI应用程序,它有2个按钮和一个状态标签.其中一个按钮将在100%的时间内重现同步和异步的死锁问题.另一个按钮调用相同的异步方法,但它包含在一个任务中,这个工作.我知道这不是一个好的编码实践,但我想理解它为什么没有相同的死锁问题.这是代码:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private async Task<string> DelayAsync()
    {
        await Task.Delay(1000);
        return "Done";
    }

    private void buttonDeadlock_Click(object sender, EventArgs e)
    {
        labelStatus.Text = "Status: Running";

        // causes a deadlock because of mixing sync and async code
        var result = DelayAsync().Result;
        // never gets here
        labelStatus.Text = "Status: " + result;
    }

    private void buttonWorking_Click(object sender, EventArgs …
Run Code Online (Sandbox Code Playgroud)

c# task async-await

9
推荐指数
2
解决办法
1018
查看次数

C#Registry SetValue抛出UnauthorizedAccessException

在您尝试使用"快速Google搜索"进行回答之前.我想指出我已经.这是情况,我有以下方法尝试修改注册表项值.我得到的问题是,当执行时,它会抛出一个UnauthorizedAccessException,即使我已经将密钥打开为可写.我以管理员身份运行Visual Studio,甚至尝试使用清单文件创建一个小的.exe,强制它以管理员身份运行,执行代码时没有运气.密钥已经存在,它不会尝试进入CreateKey方法.这是代码块.

Path = "S-1-5-21-1644491937-1078145449-682003330-5490\Software\Microsoft\Windows\CurrentVersion\Policies\System"
Key = "DisableTaskMgr"
NewValue = 1

public OperationResult ModifyKey()
    {
        OperationResult result = new OperationResult();

        if (!Path.IsNullOrEmptyTrim())
        {
            if (!Key.IsNullOrEmptyTrim())
            {
                try
                {
                    var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, true);

                    if (key != null)
                    {
                        key.SetValue(Key, NewValue);

                        key.Close();
                    }
                    else
                    {
                        result = CreateKey();
                    }
                }
                catch (Exception ex)
                {
                    result.SetFail("Error accessing registry", ex);
                }
            }
            else
            {
                result.SetFail("Registry key was null");
            }
        }
        else
        {
            result.SetFail("Registry path was null");
        }

        return result;
    }
Run Code Online (Sandbox Code Playgroud)

我是否必须手动遍历注册表树,将每个OpenSubKey调用设置为可写?我也尝试了这个,仍然犯了同样的错误......

c# registry registrykey unauthorizedaccessexcepti

8
推荐指数
2
解决办法
2万
查看次数

通过Interop为Microsoft Access创建宏

是否可以使用C#中的Interop库以与Word,Excel或PowerPoint类似的方式创建新的宏?在其他应用程序,您可以访问Microsoft.Vbe.Interop._VBComponent,它允许你注入新的宏,通过Document,WorksheetPresentation类.它看起来不像Access有类似的东西.Access有一个AllMacros列表,但它似乎是只读的.我知道如何在项目中执行宏,但我需要能够动态添加宏.我非常感谢能够指出正确方向的人.

c# macros ms-access office-interop access-vba

3
推荐指数
1
解决办法
2058
查看次数

当文件被拒绝访问而对文件被拒绝时,File.Exists的行为会有所不同

基于对MSDN文档File.Exists,该File.Exists方法应该返回false的任何错误,包括没有获得主叫用户读取文件.

我希望它false在文件被设置为FullControl拒绝给用户时返回,并FullControl拒绝用户拒绝该文件所在的目录.

我所看到的是当用户访问目录而不是文件时,File.Exists返回true; 但是,如果用户无权访问该目录,则File.Exists返回false.

我写了一个小程序来演示我在说什么:

using System;
using System.DirectoryServices;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;

namespace ConsoleApplication1
{
    internal class Program
    {
        private const string DirName = "TestDir";
        private const string FileName = "File.txt";
        private const string Password = "Password1";
        private const string UserName = "PermissionTestUser";
        private static WindowsImpersonationContext Identity = null;
        private static IntPtr LogonToken …
Run Code Online (Sandbox Code Playgroud)

c# impersonation file-io file-exists

3
推荐指数
1
解决办法
1940
查看次数