我有一个WPF GUI,我想按下一个按钮来启动一个长任务,而不会在任务期间冻结窗口.当任务正在运行时,我想获得有关进度的报告,我想在我选择的任何时候添加另一个按钮来停止任务.
我无法想出使用async/await/task的正确方法.我不能包括我尝试的所有东西,但这就是我现在拥有的东西.
一个WPF窗口类:
public partial class MainWindow : Window
{
readonly otherClass _burnBabyBurn = new OtherClass();
internal bool StopWorking = false;
//A button method to start the long running method
private async void Button_Click_3(object sender, RoutedEventArgs e)
{
Task burnTheBaby = _burnBabyBurn.ExecuteLongProcedureAsync(this, intParam1, intParam2, intParam3);
await burnTheBaby;
}
//A button Method to interrupt and stop the long running method
private void StopButton_Click(object sender, RoutedEventArgs e)
{
StopWorking = true;
}
//A method to allow the worker method to call …Run Code Online (Sandbox Code Playgroud) 我正在构建一个Metro App.
在MainPage.xaml.cs中,我实例化Album,如下所示:
Album album = new Album(2012); //With the album ID as its parameter.
ListView1.ItemsSource = album.Songs;
Run Code Online (Sandbox Code Playgroud)
在Album.cs中,构造函数如下:
public Album(int ID)
{
this.ID = ID;
Initialize(); //Serves as a wrapper because I have to call httpClient.GetStreamAsync() and "async" doesn't work for the constructor.
}
Run Code Online (Sandbox Code Playgroud)
最后,Initialize方法:
private async void Initialize()
{
//...some code...
HttpClient cli = new HttpClient();
Stream SourceStream = await HttpClient.GetStreamAsync("http://contoso.com");
//...some code...
this.Songs = Parse(SourceStream);
}
Run Code Online (Sandbox Code Playgroud)
问题是当它运行到GetStreamAsync时,它会ListView1.ItemsSource = album.Songs直接转到album.Songs null.
有这个问题的快速解决方案吗?Thx提前.
void A()
{
foreach (var document in documents)
{
var res = records.BulkWriteAsync(operationList, writeOptions); // res is Task<BulkWriteResult<JobInfoRecord>>
}
}
Run Code Online (Sandbox Code Playgroud)
foreach我想等待全部结果后BulkWriteAsync,该怎么办?我不想标记A()为async并执行以下操作
await records.BulkWriteAsync(operationList, writeOptions);
这是好的解决方案吗?
void A()
{
var tasks = new List<Task<BulkWriteResult<JobInfoRecord>>>();
foreach (var document in documents)
{
var task = records.BulkWriteAsync(operationList, writeOptions);
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
}
Run Code Online (Sandbox Code Playgroud)
如果我会标记为我从未参与过,我会打电话A()过来try catchpublic async void A()asynccatch
似乎AspNet.Core开始立即发送响应,IEnumerable而无需遍历整个集合。例如:
[HttpGet("")]
public async Task<IActionResult> GetData()
{
IEnumerable<MyData> result = await _service.GetData();
return Ok(result.Select(_mapper.MapMyDataToMyDataWeb));
}
Run Code Online (Sandbox Code Playgroud)
现在,在映射其中一个元素的过程中发生了一个异常,因此我假设有一个500响应,但是实际上发生的是,我得到的200Json只有部分(且不正确)的Json。
我认为这Asp.Net Core是提供此行为的功能而不是错误,并且通过调用eg可以相对容易地修复ToList(),但是我想知道是否存在某种标志可以阻止这种情况的发生,因为它并不能真正使这种情况发生。例如API项目和标准JSON响应的含义。
我在文档中找不到任何描述此行为以及如何防止它的内容。
PS我已经验证了呼叫可以ToList()解决此问题,并且响应为500,带有正确的异常(带有UseDeveloperExceptionPage)
我创建了一个小演示项目来帮助我了解如何使用取消令牌。我知道您取消令牌并检查是否已请求取消,但是有没有办法可以检查取消是否已实现?在下面的示例中,我不想再次运行 Work(),直到 DoWork() 完成运行。
public class Program
{
public static CancellationTokenSource tokenSource;
private static void Main(string[] args)
{
while (true)
{
Work();
}
}
public static async void Work()
{
tokenSource = new CancellationTokenSource();
Console.WriteLine("Press any key to START doing work");
Console.ReadLine();
Console.WriteLine("Press any key to STOP doing work");
DoWork(tokenSource.Token);
Console.ReadLine();
Console.WriteLine("Stopping...");
tokenSource.Cancel();
}
public static async void DoWork(CancellationToken cancelToken)
{
while (true)
{
Console.WriteLine("Working...");
await Task.Run(() =>
{
Thread.Sleep(1500);
});
if (cancelToken.IsCancellationRequested)
{
Console.WriteLine("Work Cancelled!");
return;
}
}
} …Run Code Online (Sandbox Code Playgroud) 我一直在尝试构建一个 Windows ConsoleApp 作为 WebService 运行来来回同步一些数据我已经构建了一个用于同步的项目,当我通过我的 wpf 项目运行它时,它似乎可以工作,但事实并非如此。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
using QAQC_DataCommon.Models;
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
Gettasks();
}
public static async void Gettasks()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost/QAQC_SyncWebService/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
var response = await client.GetAsync("Tasks/?username=XXXXXX&LastUpdated=1/1/15");
if (response.IsSuccessStatusCode)
{
List<QaqcRow> ls = await response.Content.ReadAsAsync<List<QaqcRow>>();
foreach (QaqcRow qaqcRow in ls)
{
Debug.WriteLine(qaqcRow.GetValue("BusinessUnit"));
}
}
}
catch (Exception) …Run Code Online (Sandbox Code Playgroud) c# ×6
asynchronous ×3
.net-4.5 ×1
.net-core ×1
asp.net-core ×1
async-await ×1
http ×1
httpclient ×1
httpresponse ×1
web-services ×1
wpf ×1