Visual Studio扩展包是否支持异步操作?
本文关键字:支持 异步操作 是否 Studio 扩展 包是否 Visual | 更新日期: 2023-09-27 18:15:51
我正在创建一个自定义的视觉工作室扩展。在它的初始化代码中,我使用async-await使异步WebRequest到远程端点。
问题是,在我调用await语句的那一刻,我的自定义扩展初始化的执行停止并且永远不会回到它。我怀疑VS扩展初始化代码在异步编程方面有些特殊。如果有人能告诉我为什么会发生这种情况,我将不胜感激。
有一个叫做AsyncPackage的新包,它允许异步加载你的包。它有一个AsyncInitialize。摘自MSDN:
您需要添加对Microsoft.VisualStudio.Shell.Interop.14.0的引用。设计时间
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();
}
}
}