在visual studio 2015社區中使用c#,嘗試將轉換base64編碼字符串的代碼轉換爲線程化任務以減少瓶頸。c#在setter中的線程
這是工作的代碼:
private string _logoBase64;
public string logoBase64
{
get { return _logoBase64; }
set
{
_logoBase64 = value;
setLogo();
}
}
public ImageSource logo { get; set; }
private void setLogo()
{
if ((this.logoBase64 != null) && (this.logoBase64.Length > 0))
{
string _logoBase64 = this.logoBase64
.Replace("data:image/png;base64,", "")
.Replace("data:image/gif;base64,", "")
.Replace("data:image/jpeg;base64,", "");
var image = new BitmapImage();
try
{
image.BeginInit();
image.StreamSource = new MemoryStream(Convert.FromBase64String(_logoBase64));
image.EndInit();
this.logo = image;
}
catch (Exception e)
{
Program.Errors.Add(e.Message + "\n" + e.StackTrace);
if (Program.environment == "development")
{
Console.WriteLine(e.Message);
}
}
}
}
使用this例如,我試圖將其轉換爲一個線程任務:
internal Task setLogoASync(string b64, CancellationToken cancellationToken)
{
return Task.Run(() =>
{
var image = new BitmapImage();
if ((b64 != null) && (b64.Length > 0))
{
b64 = b64
.Replace("data:image/png;base64,", "")
.Replace("data:image/gif;base64,", "")
.Replace("data:image/jpeg;base64,", "");
try
{
image.BeginInit();
image.StreamSource = new MemoryStream(Convert.FromBase64String(b64));
image.EndInit();
this.logo = image;
}
catch (Exception e)
{
Program.Errors.Add(e.Message + "\n" + e.StackTrace);
if (Program.environment == "development")
{
Console.WriteLine(e.Message);
}
}
}
this.logo = image;
}, cancellationToken);
}
但問題是二傳手必須是異步,但它不可能。有沒有解決的辦法?
的制定者通常的建議是,他們應該只用於非常短的運行操作之前。最好是完全刪除它,只是提供一個公共方法 – thumbmunkeys
你可以在setter中使用線程或BackgroundWorker,並讓setter繼續而不停止你的GUI –
Saad Mind告訴我到底如何? – pgee70