gpt4 book ai didi

c# - Visual Studio 扩展包是否支持异步操作

转载 作者:太空宇宙 更新时间:2023-11-03 21:07:20 25 4
gpt4 key购买 nike

我正在创建一个自定义的 visual studio 扩展。在其初始化代码中,我使用 async-await 将异步 WebRequest 发送到远程端点。

问题是在我调用 await 语句的那一刻,我的自定义扩展初始化的执行停止并且永远不会返回。我怀疑 VS 扩展初始化代码在异步编程方面有些特殊。如果有人能指出我为什么会这样,我将不胜感激。

最佳答案

有一个名为 AsyncPackage 的新包,它允许异步加载您的包。它有一个 AsyncInitialize。摘自 MSDN:

您需要添加对 Microsoft.VisualStudio.Shell.Interop.14.0.DesignTime 的引用才能正常工作

using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using System.Threading;
using System.Runtime.CompilerServices;
using System.IO;

namespace asyncpackagetest
{
[ProvideService((typeof(STextWriterService)), IsAsyncQueryable = true)]
[ProvideAutoLoad(VSConstants.UICONTEXT.NoSolution_string, PackageAutoLoadFlags.BackgroundLoad)]
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(VSPackage1.PackageGuidString)]
public sealed class VSPackage1 : AsyncPackage
{

public const string PackageGuidString = "3dc186f8-2146-4d89-ac33-e216b3ead526";

public VSPackage1()
{

}

protected override async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
this.AddService(typeof(STextWriterService), CreateService);
await base.InitializeAsync(cancellationToken, progress);
ITextWriterService textService = await this.GetServiceAsync(typeof(STextWriterService)) as ITextWriterService;
await textService.WriteLineAsync(@"c:\windows\temp\async_service.txt", "this is a test");

}

public async System.Threading.Tasks.Task<object> CreateService(IAsyncServiceContainer container, CancellationToken cancellationToken, Type serviceType)
{
STextWriterService service = null;
await System.Threading.Tasks.Task.Run(() => {
service = new TextWriterService(this);
});

return service;
}

public class TextWriterService : STextWriterService, ITextWriterService
{
private Microsoft.VisualStudio.Shell.IAsyncServiceProvider serviceProvider;
public TextWriterService(Microsoft.VisualStudio.Shell.IAsyncServiceProvider provider)
{
serviceProvider = provider;
}
public async System.Threading.Tasks.Task WriteLineAsync(string path, string line)
{
StreamWriter writer = new StreamWriter(path);
await writer.WriteLineAsync(line);
writer.Close();
}
public TaskAwaiter GetAwaiter()
{
return new TaskAwaiter();
}
}
public interface STextWriterService
{
}
public interface ITextWriterService
{
System.Threading.Tasks.Task WriteLineAsync(string path, string line);
TaskAwaiter GetAwaiter();
}
}
}

关于c# - Visual Studio 扩展包是否支持异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40345756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com