Come si codifica un gestore di eventi WPF asincrono (o Windows Form) in F #? In particolare, c'è qualche schema di codifica che approssima asincrono C# 5 e attendi?F # handler di eventi asincroni per WPF simili a asincroni di C# e attendi
Qui è una completa applicazione C# WPF:
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
class Program
{
static int IncrementSlowly(int previous)
{
Thread.Sleep(3000);
if (previous == 2) throw new Exception("Oops!");
return previous + 1;
}
static async void btn_Click(object sender, RoutedEventArgs e)
{
var btn = sender as Button;
btn.IsEnabled = false;
try
{
var prev = (int)btn.Content;
btn.Content = await Task.Run(() => IncrementSlowly(prev));
}
catch (Exception ex)
{
btn.Content = ex.Message;
}
finally
{
btn.IsEnabled = true;
}
}
[STAThread]
static void Main(string[] args)
{
var btn = new Button() { Content = 0 };
var win = new Window() { Content = btn };
btn.Click += btn_Click;
new Application().Run(win);
}
}
Sto avendo difficoltà a capire ciò che l'equivalente sarebbe utilizzando F #. Ho fatto diversi tentativi usando combinazioni di flussi di lavoro asincroni e metodi Asincroni. Diventa davvero complicato molto velocemente. Spero che ci sia un modo semplice che sto solo trascurando.
Ecco il mio punto di partenza, che blocca l'interfaccia utente a btn.Content <- incrementSlowly prev
. Cosa faccio dopo?
open System
open System.Threading
open System.Threading.Tasks
open System.Windows
open System.Windows.Controls
let incrementSlowly previous =
Thread.Sleep(3000)
if previous = 2 then failwith "Oops!"
previous + 1
let btn_Click (sender : obj) e =
let btn = sender :?> Button
btn.IsEnabled <- false
try
try
let prev = btn.Content :?> int
btn.Content <- incrementSlowly prev
with ex -> btn.Content <- ex.Message
finally
btn.IsEnabled <- true
[<EntryPoint>][<STAThread>]
let main _ =
let btn = new Button(Content = 0)
let win = new Window(Content = btn)
btn.Click.AddHandler(RoutedEventHandler(btn_Click))
Application().Run(win)
A tal proposito, supporre che incrementSlowly
non possa essere modificato.
Questo articolo dovrebbe essere utile http://tomasp.net/blog/csharp-fsharp- async-intro.aspx/ –