c#-5.0

How to wait until all tasks are finished before running code

风格不统一 提交于 2019-11-30 22:48:31
I am trying to write a multi threading search and then display all the results once the tasks have finished running but currently I don't understand how to process the results once all the tasks are complete My code is as follows: private async void DoSearchAsync() { var productResults = await SearchProductsAsync(CoreCache.AllProducts); var brochureResults = await SearchBrochuresAsync(CoreCache.AllBrochures); _searchResults.AddRange(productResults); _searchResults.AddRange(brochureResults); ResultsCount = _searchResults.Count; } Where _searchResults is a List<SearchResult> My understanding is

What can I do in C# 5 with .Net 4.5 that I couldn't do in C# 4 with .Net 4? [closed]

折月煮酒 提交于 2019-11-30 22:18:00
问题 Closed . This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 4 years ago . I have Visual Studio 2012 RC installed on Windows 8 Release Preview and my question is are there any useful new features not related to Metro, or is Metro what seperates .Net 4 and .Net 4.5? 回答1: See What's New in the .NET Framework 4.5 and What's New for Visual C# in Visual

Store image in to StorageFile from image control

微笑、不失礼 提交于 2019-11-30 20:56:42
问题 how can i store image in to StorageFile from image control in windows store apps? I'm using following link but that is not useful for me StorageFile file = await StorageFile.CreateStreamedFileFromUriAsync(" ", new Uri(user.ProfilePicUrl), new RandomAccessStream()); http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.storagefile.createstreamedfileasync.aspx I need clear solution for my problem. How can I do this? 回答1: You can use the following method to save an image from an

ContinueWith loses the SynchronizationContext

不想你离开。 提交于 2019-11-30 18:40:48
问题 In the snippet below, the SynchronizationContext is lost, and because of that also the CurrentCulture and CurrentUICulture . Log() comes from this answer. public async Task<ActionResult> Index() { Log("before GetAsync"); await new HttpClient().GetAsync("http://www.example.com/") .ContinueWith(request => { Log("ContinueWith"); request.Result.EnsureSuccessStatusCode(); }, TaskContinuationOptions.AttachedToParent); return View(); } static void Log(string message) { var ctx = System.Threading

Why return type of async must be void, Task or Task<T>

放肆的年华 提交于 2019-11-30 18:22:26
I am trying get my hands dirty with async CTP and I noticed that the compiler complains about the async return type. What is the problem with other types? A simple demo static void Main(string[] args) { DoWork(); Console.WriteLine("Returned to main"); Console.Read(); } // why do I need to return void, Task or Task<T> here? // I know I can use something like Task<IEnumerable<string>> private static async string[] DoWork() { Console.WriteLine("DoWork started"); return await Task.Factory.StartNew( delegate { Thread.Sleep(2000); Console.WriteLine("DoWork done"); return new List<string>(); }); }

How to write C# 5 async?

帅比萌擦擦* 提交于 2019-11-30 18:04:24
问题 I have the following scenario: When a command is inputted (for test, it's a console application, when it's ready, I hope it will be a WebService) I execute some code, and when further user input is needed, I return to the command interpreter immediately. When the new input is given, I want processing to resume from where I left it. That sounds so much like c#5 async-await pattern, that I decided to give it a try. I was thinking about this: public void CommandParser() { while(true) { string s

Reading from serial port asynchronously using Async await method

只谈情不闲聊 提交于 2019-11-30 17:30:53
问题 I'm using this way for reading from serial port : public static void Main() { SerialPort mySerialPort = new SerialPort("COM1"); mySerialPort.BaudRate = 9600; mySerialPort.Parity = Parity.None; mySerialPort.StopBits = StopBits.One; mySerialPort.DataBits = 8; mySerialPort.Handshake = Handshake.None; mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); mySerialPort.Open(); Console.WriteLine("Press any key to continue..."); Console.WriteLine(); Console.ReadKey();

Why does cancellation block for so long when cancelling a lot of HTTP requests?

假装没事ソ 提交于 2019-11-30 15:26:47
Background I have some code that performs batch HTML page processing using content from one specific host. It tries to make a large number (~400) of simultaneous HTTP requests using HttpClient . I believe that the maximum number of simultaneous connections is restricted by ServicePointManager.DefaultConnectionLimit , so I'm not applying my own concurrency restrictions. After sending all of the requests asynchronously to HttpClient using Task.WhenAll , the entire batch operation can be cancelled using CancellationTokenSource and CancellationToken . The progress of the operation is viewable via

Convert async lambda expression to delegate type System.Func<T>?

主宰稳场 提交于 2019-11-30 12:32:17
问题 I have an async method inside a portable class library with this signature: private async Task<T> _Fetch<T>(Uri uri) It fetches a resource that is cast back as a concrete type T. I'm working with a 3rd party cache library (Akavache) that requires a Func<T> as one of the parameters and have tried to do so in this manner: await this.CacheProvider.GetOrCreateObject<T>(key, async () => await _Fetch<T>(uri), cacheExpiry); This results in the error: Cannot convert async lambda expression to

Cold Tasks and TaskExtensions.Unwrap

99封情书 提交于 2019-11-30 10:29:04
I've got a caching class that uses cold (unstarted) tasks to avoid running the expensive thing multiple times. public class AsyncConcurrentDictionary<TKey, TValue> : System.Collections.Concurrent.ConcurrentDictionary<TKey, Task<TValue>> { internal Task<TValue> GetOrAddAsync(TKey key, Task<TValue> newTask) { var cachedTask = base.GetOrAdd(key, newTask); if (cachedTask == newTask && cachedTask.Status == TaskStatus.Created) // We won! our task is now the cached task, so run it cachedTask.Start(); return cachedTask; } } This works great right up until your task is actually implemented using C#5's