Tag: task

获取任务的方法名称

我希望从C#中的任务中获取方法/操作名称。 具体来说,我正在实现一个自定义任务调度程序,并希望生成有关任务运行持续时间的统计信息,然后我将通过在任务内部运行的方法进行聚合。 在visual studio调试器中,您可以访问它并查看m_action私有变量以及调试器显示注释,并将其显示为Method = {0}。 有没有办法从任务本身访问这个?

在ContinueWith()块中使用await

我有以下代码: var result = MessageBoxHelper.MsgBox .ShowAsync(“Press Yes to proceed”, MessageBoxButton.YesNo) .ContinueWith((answer) => { if (answer.Result == MessageBoxResult.Yes) { Task asyncTask = ExecuteAsyncFunc(); //asyncTask.Unwrap(); ?? asyncTask.ContinueWith((a) => { // More }, TaskContinuationOptions.OnlyOnRanToCompletion); } }, TaskContinuationOptions.OnlyOnRanToCompletion); } 像这样在其他地方调用: public async Task ExecuteAsyncFunc() { await CallAnotherAsyncFunction(); } 我相信我需要调用Unwrap(),我试过,因为我在ContinueWith()块中调用await。 但是,当我取消注释时,我收到以下错误: 错误CS1929’Task’不包含’Unwrap’的定义,最好的扩展方法重载’TaskExtensions.Unwrap(Task)’需要’Task’类型的接收器 我是否需要在此上下文中使用Unwrap,如果是这样,我做错了什么?

任务IsCanceled是假的,而我取消了

当我取消任务时,等待结果仍然为IsCanceled属性返回true。 似乎有些事情出了问题。 请指教。 这是代码: CancellationTokenSource _cancelLationToken = new CancellationTokenSource(); private async void Button_Click(object sender, EventArgs e) { _cancelLationToken = new CancellationTokenSource(); _cancelLationToken.Token.Register(theCallBack); var myTaskToWaitFor = Task.Factory.StartNew(() => WorkHard(_cancelLationToken.Token), _cancelLationToken.Token); await myTaskToWaitFor; int i=0; if(myTaskToWaitFor.IsCanceled) i = i; //breakpoint for debugging else i = i; //breakpoint for debugging <== always ends here… 🙁 } private void […]

如何使用CancellationToken取消任务?

所以我有这个代码: //CancelationToken CancellationTokenSource src = new CancellationTokenSource(); CancellationToken ct = src.Token; ct.Register(() => Console.WriteLine(“Abbruch des Tasks”)); //Task Task t = new Task(() => { System.Threading.Thread.Sleep(1000); if (ct.IsCancellationRequested) { try { //Throw ct.ThrowIfCancellationRequested(); } catch (OperationCanceledException) { Console.WriteLine( “ThrowIfCancellationRequested() liefert eben eine Exception”); } } }, ct); //Run Task and Cancel t.Start(); src.CancelAfter(350); t.Wait(); // Get […]

Excel Interop:使用Task.Run创建实例会导致exceptionSystem.EntryPointNotFoundException

这是我产生问题的最小例子: using System.Runtime.InteropServices; using System.Threading.Tasks; using Excel = Microsoft.Office.Interop.Excel; class Program { static void Main(string[] args) { Task.Run(() => { Excel.Application app = new Excel.Application(); if (app != null) { app.Quit(); Marshal.FinalReleaseComObject(app); app = null; } }); } } 这导致以下exception: 日语的最后一部分说”EventSetInformation” of DLL advapi32.dll entry point cannot be found的”EventSetInformation” of DLL advapi32.dll entry point cannot […]

Task.WhenAll()和foreach(任务中的var任务)之间的区别是什么

经过几个小时的挣扎,我在我的应用程序中发现了一个错误。 我认为下面的两个函数具有相同的行为,但事实certificate它们没有。 任何人都可以告诉我幕后真的发生了什么,以及他们为什么会以不同的方式行事? public async Task MyFunction1(IEnumerable tasks){ await Task.WhenAll(tasks); Console.WriteLine(“all done”); // happens AFTER all tasks are finished } public async Task MyFunction2(IEnumerable tasks){ foreach(var task in tasks){ await task; } Console.WriteLine(“all done”); // happens BEFORE all tasks are finished }

等待Task.CompletedTask什么?

我使用在Build2017中引入的Windows Template Studio创建了UWP应用程序。 下面的类是它生成的代码的一部分。 public class SampleModelService { public async Task<IEnumerable> GetDataAsync() { await Task.CompletedTask; // <– what is this for? var data = new List(); data.Add(new SampleModel { Title = “Lorem ipsum dolor sit 1”, Description = “Lorem ipsum dolor sit amet”, Symbol = Symbol.Globe }); data.Add(new SampleModel { Title = “Lorem ipsum dolor […]

如何在Windows 10中的c#中的异步方法中从返回的任务中提取数据

如何从下面的foreach循环中的getResponseFromUrl的返回值中提取数据:这里我无法从返回的值中提取数据。 我正在windows 10通用应用程序开发中构建一个应用程序。 var response = NetworkingCalls.getResponseFromUrl(url, requestDictionary); foreach (KeyValuePair item in response) { Util.debugLog(item.Key.ToString(), item.Value.ToString()); } 这是返回字典的模型代码 using System; using System.Collections.Generic; using System.Threading.Tasks; using Windows.Storage.Streams; using Windows.Web.Http; namespace App2.WrittenLibraries { class NetworkingCalls { public async static Task<Dictionary> getResponseFromUrl(string urlString, Dictionary requestDictionary) { var client = new HttpClient(); Uri url = new Uri(urlString); var requestToSend […]

清理TPL中的CallContext

根据我是使用基于异步/等待的代码还是基于TPL的代码,我在清理逻辑CallContext遇到两种不同的行为。 如果我使用以下async / await代码,我可以完全按照我的预期设置和清除逻辑CallContext : class Program { static async Task DoSomething() { CallContext.LogicalSetData(“hello”, “world”); await Task.Run(() => Debug.WriteLine(new { Place = “Task.Run”, Id = Thread.CurrentThread.ManagedThreadId, Msg = CallContext.LogicalGetData(“hello”) })) .ContinueWith((t) => CallContext.FreeNamedDataSlot(“hello”) ); return; } static void Main(string[] args) { DoSomething().Wait(); Debug.WriteLine(new { Place = “Main”, Id = Thread.CurrentThread.ManagedThreadId, Msg = CallContext.LogicalGetData(“hello”) }); } […]

强制任务到不同的核心?

Tpl和Plinq自动将工作分配给线程(在核心/ s … { 好吧,如果#threads> #cores那么,> 1个线程将在同一个核心上运行。 })。 但是,假设我有MyMethod1(){..}和MyMethod2(){..} ,我需要确保 (!)每个都运行在不同的核心上! (例如密集计算) 我找到的最近的解决方案是Plinq的.WithExecutionMode (ParallelExecutionMode.ForceParallelism) 但这是针对一种不同的情况,Plinq可能会认为按顺序而不是平行进行更好。同时,我不使用Plinq。 我只有2种方法需要在不同的核心上运行。 我该怎么做 ? ps这里有一个答案,建议使用TaskCreationOptions.LongRunning但它只是暗示TaskScheduler它应该更积极地创建线程池线程。 但是那些线程可以在同一个核心上。 我的情况要求他们处于不同的核心。 谢谢。