2017-09-22 47 views
0

您可以通過一個通過以下代碼增加和減少數字。如何通過RepeatButton增加和減少一百個數字?

以下代碼是okey。

<Window x:Class="WpfApplication1.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="400"> 
<Grid> 
    <RepeatButton Width="100" Height="40" HorizontalAlignment="Left" Name="btnRemove" Content="Remove" Click="btnRemove_Click" /> 
    <TextBox Width="150" Height="40" Name="txtDisplay" TextAlignment="Center" Text="5000" MaxLength="5" /> 
    <RepeatButton Width="100" Height="40" HorizontalAlignment="Right" Name="btnAdd" Content="Add" Click="btnAdd_Click" /> 
</Grid> 
</Window> 

...

Namespace WpfApplication1 

Partial Public Class MainWindow 

    Public counter As Integer = 5000 

    Private Sub btnAdd_Click(sender As Object, e As RoutedEventArgs) 
     txtDisplay.Text = (System.Threading.Interlocked.Increment(counter)).ToString() 
    End Sub 

    Private Sub btnRemove_Click(sender As Object, e As RoutedEventArgs) 
     txtDisplay.Text = (System.Threading.Interlocked.Decrement(counter)).ToString() 
    End Sub 

End Class 

End Namespace 

問:

如何提高和降低數字嗎?

回答

2

這個怎麼樣?

Private Sub btnAdd_Click(sender As Object, e As RoutedEventArgs) 
    counter += 100 
    If (counter > 6000) Then 
     counter = 6000 
    End If 
    txtDisplay.Text = counter.ToString() 
End Sub 

Private Sub btnRemove_Click(sender As Object, e As RoutedEventArgs) 
    counter -= 100 
    If (counter < 0) Then 
     counter = 0 
    End If 
    txtDisplay.Text = counter.ToString() 
End Sub 

沒有理由在這裏使用System.Threading.Interlocked.Increment因爲事件處理程序總是相同的線程上執行。

3

所以你的問題是關於線程安全遞增/遞減?您可以使用Interlocked.Add

Private Sub btnAdd_Click(sender As Object, e As RoutedEventArgs) 
    txtDisplay.Text = System.Threading.Interlocked.Add(counter, 100).ToString() 
End Sub 

Private Sub btnRemove_Click(sender As Object, e As RoutedEventArgs) 
    txtDisplay.Text = System.Threading.Interlocked.Add(counter, -100).ToString() 
End Sub 
+0

@MarkoMarkowitz:在我的代碼再看看;)根據你的示例代碼 –

+0

?礦。在不同的(多線程)應用程序中?最有可能是蒂姆的。 – mm8

+0

@MarkoMarkowitz:什麼意思最好?你已經在使用'Threading.Interlocked.Increment' /'Decrement'。所以我想你有理由使用這種線程安全的方法。直接修改counter字段不是線程安全的。但是如果沒有多個線程同時修改它,那就沒關係。所以只有你知道你需要什麼。 –

相關問題