我是使用async修饰符进行异步编程的新手.我试图弄清楚如何确保我Main的控制台应用程序的方法实际上异步运行.
class Program
{
static void Main(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = bs.GetList();
}
}
public class Bootstrapper {
public async Task<List<TvChannel>> GetList()
{
GetPrograms pro = new GetPrograms();
return await pro.DownloadTvChannels();
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这不是从"顶部"异步运行的.由于无法async在Main方法上指定修饰符,如何在main异步中运行代码?
在 .Net core 中,我们可以使用 IHttpClientFactory 在运行时注入和使用。作为开发人员,我无需担心依赖项解析。我只需要在服务集合中指定 AddHttpClient() 。同样,如何在 WPF 应用程序、.net 框架 4.6.1 中使用 IHttpClientFactory?由于没有可用于 WPF 应用程序的服务集合,因此不了解如何解决依赖关系。
我已经阅读了使用HttpClientFactory 的热门博客文章https://www.stevejgordon.co.uk/introduction-to-httpclientfactory-aspnetcore
引用它
ASP.NET Core 2.1中将出现一个新的HttpClientFactory功能,它有助于解决开发人员在使用HttpClient实例从其应用程序发出外部Web请求时可能遇到的一些常见问题.
所有示例都显示在asp.net应用程序的启动类中连接它,例如
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddHttpClient();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是你可以在ASP.NET核心之外使用吗?如果是这样的例子
我会想到很多非Web应用程序(.net核心应用程序)需要进行Web调用,那么为什么这不是.net core api的一部分而不是放入asp.net core api
我在两个 WebApi 之间发送大(20GB)文件时遇到问题。
WebAPI1 编写于ASP.NET 4.6
WebAPI2 编写于ASP.NET Core 2.0
当我通过 Postman 将此文件发送到 WebAPI2 时,整个文件都会被发送。但是,当我尝试将文件从 WebAPI1 发送到 WebAPI2 时,它失败了(不过我可以发送 7GB 之类的文件)。
在发送 20GB 文件期间,我在 WebAPI2 中收到错误:
Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Unexpected
end of request content.
at Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.PipeCompl
etion.ThrowFailed()
at Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.Pipe.GetR
esult(ReadResult& result)
at Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.Pipe.Micr
osoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.IReadableBufferAwai
ter.GetResult()
at Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.ReadableB
ufferAwaitable.GetResult()
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.<ReadAs
ync>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameRequestStream.
<ReadAsyncInternal>d__21.MoveNext()
--- End of stack trace …Run Code Online (Sandbox Code Playgroud) 有时获取ASP.NET MVC5 WebAPI令牌失败
码
string GetAPITokenSync(string username, string password, string apiBaseUri)
{
var token = string.Empty;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.Timeout = TimeSpan.FromSeconds(60);
//setup login data
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password),
});
//send request
Task t = Task.Run(() =>
{
HttpResponseMessage responseMessage = client.PostAsync("/Token", formContent).Result;
var responseJson = responseMessage.Content.ReadAsStringAsync().Result;
var jObject = JObject.Parse(responseJson);
token = jObject.GetValue("access_token").ToString();
}); …Run Code Online (Sandbox Code Playgroud) 因此,我在使用任务来处理 HTTP 请求负载时遇到了一些困难。
我想做的是从 WMTS 创建一个大图像。对于那些不知道的人来说,WMTS 是一种网络地图切片服务。因此基本上,您可以通过发送包含正确的tileRow 和tileColumn 的请求来请求256x256 的图像图块。因此,在本例中,我尝试构建包含数百甚至数千个此类图像图块的图像。
为此,我创建了一个应用程序:
正如您所想象的那样,瓷砖的数量呈指数级增长。这并不会真正影响 CPU 工作,但主要是 I/O 密集型工作。因此,我认为在发送下一个请求之前,不要等待每个请求返回,而是使用任务来完成此任务。创建将处理每个单独请求的任务,并在所有任务完成后构建大图像。
所以这是我已经知道我要请求什么图块的方法。在这里,我想递归地发送带有任务的请求,直到所有数据完成(最终使用最大重试机制)。
public Dictionary<Tuple<int, int>, Image> GetTilesParallel(List<Tuple<int, int>> tileMatrix, int retry = 0)
{
//The dictionary we will return
Dictionary<Tuple<int, int>, Image> images = new Dictionary<Tuple<int, int>, Image>();
//The dictionary that we will recursively request if tiles fail.
List<Tuple<int, int>> failedTiles = new List<Tuple<int, int>>();
//To track when tasks are finished
List<Task> tasks = new List<Task>();
foreach …Run Code Online (Sandbox Code Playgroud) 我使用以下代码将文件上传到dropbox.
我正在使用nuget包Dropbox.Api并获取异常System.Threading.Tasks.TaskCanceledException("任务被取消.")
从这个SO问题看来,它似乎是一个超时问题.
那么如何修改以下代码来设置超时.
public async Task<FileMetadata> UploadFileToDropBox(string fileToUpload, string folder)
{
DropboxClient client = new DropboxClient(GetAccessToken());
using (var mem = new MemoryStream(File.ReadAllBytes(fileToUpload)))
{
string filename = Path.GetFileName(fileToUpload);
try
{
string megapath = GetFullFolderPath(folder);
string megapathWithFile = Path.Combine(megapath, Path.GetFileName(Path.GetFileName(filename))).Replace("\\", "/");
var updated = client.Files.UploadAsync(megapathWithFile, WriteMode.Overwrite.Instance, body: mem);
await updated;
return updated.Result;
}
catch (Exception ex)
{
return null;
}
}
}
Run Code Online (Sandbox Code Playgroud) c# ×5
.net ×3
asp.net-core ×2
.net-core ×1
asynchronous ×1
c#-4.0 ×1
dropbox-api ×1
httpclient ×1
token ×1